10

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.

Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122

2 Answers2

11

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
nkjt
  • 7,825
  • 9
  • 22
  • 28
9

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.

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
  • 1
    Thanks, I did not realize this would be interpreted as a function call if the function doesn't exist. Wish I could accept this answer as well. – Dennis Jaheruddin Aug 13 '13 at 11:12