Question

In Matlab, I have typed the following commands:

>> a = [1 2; 3 4]

a =

     1     2
     3     4

When I tried the command a^2, I got the following:

>> a^2

ans =

     7    10
    15    22

I was actually expecting to get:

ans =

       1     4
       9     16

In other words, I was expecting to get each element of the matrix to be raised to 2.

Why was the result as shown above?

Thanks.

Was it helpful?

Solution

In MATLAB, all single-character operators are matrix operators. So, you are using the matrix power, e.g.,

a^2 == a*a

if you want to square each element, you'll have to use the element-wise power operator:

>> a.^2
ans = 
    1   4
    9   16

Read more about MATLAB's operators here.

OTHER TIPS

When you type a^2 in Matlab, what you are actually executing is a*a (Matrix multiplication). If you want element-wise operations in Matalb, you need to type

a.^2

Note the difference between ^2 and .^2 !
The little dot . before the operand marks an element-wise operation, as opposed to matrix operation.

The same goes for other operations, such as / vs ./, * vs. .*, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top