22

Is it possible in Matlab to increment a value of a variable without restating it on the right hand side of the statement?

1
  • I don't believe so. Did you try it?
    – Ben Voigt
    Jul 9, 2011 at 21:59

2 Answers 2

19

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.

6
  • 9
    I'm not sure why you claim it would be ambiguous. X op= e would mean X = (X) op e, but only evaluate X once, just like in C, C++, Java, C#, etc. The fact that Octave DOES support these is proof that there's no fundamental ambiguity.
    – Ben Voigt
    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)
    – Ben Voigt
    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 the X = (X) op e form. E.g. a = 1; a([1 1 1]) = a([1 1 1]) + a(1); already has behavior. Or try a = 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
  • 1
    Hit comment character limit. The real analagous X = X op e code is a = 1; a([1 1 1]) = a([1 1 1]) + [2 3 4]. Gives me 5 in R2009b. Jul 11, 2011 at 15:50
  • 1
    What 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..
    – eric
    Oct 30, 2016 at 2:59
7

MatLab doesn't have compound assignment, but the open-source clone Octave does.

Source: http://hyperpolyglot.org/numerical-analysis

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.