Reputation: 21563
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.
Upvotes: 10
Views: 832
Reputation: 7817
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
Upvotes: 11
Reputation: 9864
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.
Upvotes: 9