简体   繁体   中英

Matlab - matrix to the power of 2

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.

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM