Is it possible in Matlab to increment a value of a variable without restating it on the right hand side of the statement?
2 Answers
AFAIK, there's no such thing in MATLAB.
And this is understandable(look at Steven Lord's answer, post 11).
That post indicates that since MATLAB is array based, such operator would be ambiguous and unintuitive, at best.
-
9I'm not sure why you claim it would be ambiguous.
X op= e
would meanX = (X) op e
, but only evaluateX
once, just like in C, C++, Java, C#, etc. The fact that Octave DOES support these is proof that there's no fundamental ambiguity. Jul 9, 2011 at 22:03 -
1
a([1 1 1])
has bigger ambiguity problems already, since it could be interpreted either as a vector of indices or as a logical vector.a([1 2 1])
is a better example, but there's only only interpretation consistent with other languages. (And sorry, I only read up to post 10 the first time I checked that discussion) Jul 9, 2011 at 22:21 -
3
a([1 1 1])
is unambiguous: it's numeric indexes, because the literal "1" is a double in Matlab, and Matlab won't convert to logicals in the index context.a([true true true])
would be logical indexes. That aside, Ben Voigt's comment makes total sense:+=
is a simple syntactic shorthand. Steven Lord's post doesn't really explain it; the weird edge cases Lord cites already occur in Matlab with theX = (X) op e
form. E.g.a = 1; a([1 1 1]) = a([1 1 1]) + a(1);
already has behavior. Or trya = 1; a([1 1 1]) = a(1) + [2 3 4];
. (It gives me 5.) Adding+=
wouldn't make this any worse. Jul 11, 2011 at 15:45 -
1Hit comment character limit. The real analagous
X = X op e
code isa = 1; a([1 1 1]) = a([1 1 1]) + [2 3 4]
. Gives me 5 in R2009b. Jul 11, 2011 at 15:50 -
1What Steve Lord gave was excuses and obfuscation. Octave does it. It's idiotic especially when you use good (pythonic) naming conventions to have to write it all out..– ericOct 30, 2016 at 2:59
MatLab doesn't have compound assignment, but the open-source clone Octave does.