I wanted to plot the following
y=linspace(0,D,100)
temp=y^2;
plot(y,temp);
i am getting an error with y^2
, it says matrix should be square.
is there another way to plot.
You are not getting that error because of plot. You are getting it because of
temp=y^2
Instead, you should be using
temp=y.^2
^
means matrix power. .^
is elementwise power. You can find more about MATLAB operators here.
Let's say you have a 3x3 matrix, magic(3).
A=magic(3)
A =
8 1 6
3 5 7
4 9 2
Here is square of matrix A (which is A*A, as Dan suggested):
A^2
ans =
91 67 67
67 91 67
67 67 91
Here is the matrix which contains squares of A's elements:
A.^2
ans =
64 1 36
9 25 49
16 81 4
A^2
is the same as A*A
(i.e. matrix multiplication with self) to the explanation since you have already written out a numerical example.
Just as an alternative to the above answer, you can consider the following case:
A = magic(3);
temp = bsxfun(@times,A,A);
which retrieves the same results as
temp = A.^2;
the .
operator will apply your square element-wise. bsxfun
makes exactly the same.
I hope this helps.