Reputation: 415
File abc.m has
function [] = abc(N)
N += 1;
When I try to execute abc by passing any number (e.g. 5) for N, I get the error "N" was previously used as a variable, conflicting with its use here as the name of a function. It gives the error in the line N += 1;
But I do not understand where I am using N as a function name.
Upvotes: 2
Views: 1525
Reputation: 14939
The correct syntax is N = N + 1
, as David points out. However, if you think the error message you get seems strange, I've provided an explanation below.
This has to do with how MATLAB recognizes command syntax. Depending on where you put your spaces, MATLAB interprets commands differently.
Note that you get the same error message for N +* 1
or N +*-
+=
, +*-
, **0
etc, are not correct syntax in MATLAB. Therefore MATLAB must take a guess at what you're attempting to do.
If you didn't have any spaces before +=
, according to MATLAB it would have to be an operation on variables. You will therefore get the error message: "Error: The expression to the left of the equals sign is not a valid target for an assignment".
The space in front of +=
makes this look like either an operation on variables, or an attempt at using N
as a function (similar to ls
, disp
, whos
etc).
Normally, the space on both sides of +=
would mean this was an operation on variables. However, +=
operator is not on the list of "Operators and Elementary Operations", so that possibility can be ruled out. The only possible valid use of this syntax is if this is a function that can take strings as input.
The syntax is actually correct in some cases (though useless), for instance:
whos += 0 %// Gives no errors
but:
whos = 1;
whos += 1;
??? Error: "whos" was previously used as a variable,
conflicting with its use here as the name of a function
or command.
So to sum it up: MATLAB sees N += 1
goes through the list of possibilities and ends up interpreting N
as a function, since that's the only possible case where it would be a valid syntax.
If you define a function N
this way, you won't get any error messages:
function varargout = N(varargin)
varargout{1} = 'You see, no errors';
end
N += 0
ans =
You see, no errors
Upvotes: 4
Reputation: 8459
N+=1
is not valid Matlab syntax, you have to do N=N+1
. I believe it is valid Octave syntax though.
Upvotes: 2