10
votes

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.

2
Can you reproduce this after restarting Matlab? - Dan
@Dan Indeed it can easily be reproduced, I think the answers explain it. - Dennis Jaheruddin
I see, I tried it in Octave and had no issues. - Dan
I think one clue is the syntax coloring of the *1 in the line that gives the problem... - Floris

2 Answers

11
votes

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
9
votes

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.