Error using simple matrix multiplication

余生颓废 提交于 2019-12-10 02:04:37

问题


I stumbled upon an error during a simple multiplication that rather surprised me. What is happening here, I always assumed * was only for matrix multiplication.

x = 2;
y = zeros(1,4);
y(1) = 1 *x;
y(2) = x* 1;
y(3) = (x *1);
y(4) = x *1;
y
x *1

Will give the following output:

y =

     2     2     2     1

Error: "x" was previously used as a variable,
conflicting with its use here as the name of a function or command.
See MATLAB Programming, "How MATLAB Recognizes Function Calls That Use Command Syntax" for details.

Does anyone understand what is going on here? Of course I verified that x is not a function.


回答1:


It depends on the spacing. See also here for a longer explanation and some examples of when you could have genuine ambiguity, but basically the first three of these will work as you expected, and the last will assume you are trying to call a function x with input *1:

x*1  
x * 1 
x* 1
x *1

This doesn't happen if you assign the output to some variable, regardless of spacing:

y(2) = x *1
z = x *1
x = x *1



回答2:


This happens because when you have x *1 in a separate line, MATLAB interprets x as a function an tries to pass '*1' as an argument to it, but then it realzes that x is a variable, hence the error.



来源:https://stackoverflow.com/questions/18206816/error-using-simple-matrix-multiplication

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