Matlab - matrix to the power of 2

可紊 提交于 2021-02-04 19:55:08

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14497839/matlab-matrix-to-the-power-of-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!