0

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.

2 Answers 2

8

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
1
  • May be worth adding that 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.
    – Dan
    Apr 5, 2013 at 7:33
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.