2

Is there a shortcut statement that would do what C code i++ would do? (that is to increase i by 1)?

Of course i do not mean the obvious i = i + 1.

Giacomo Alessandroni
  • 696
  • 1
  • 14
  • 28

2 Answers2

8

No, you cannot do this in Matlab. To increment a variable, you must use i = i + 1;.


Edit - If you were really desperate for something like this, you could define a function that looked like

function increment(x)
    evalin('caller', sprintf('%s = %s + 1;', x, x));
end

and call it like this

>> x = 1;
>> increment x;
>> x
x =
    2

however this would be (a) confusing and (b) slow.

Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
  • Sorry. `i++` is more cool. :-) And thank you, almost forgot. – Giacomo Alessandroni Feb 18 '15 at 10:42
  • 1
    Thank you for your suggestion, but I think that `i = i + 1` is more performant. – Giacomo Alessandroni Feb 18 '15 at 10:48
  • 1
    I'm not sure @Chris really intends anyone to use his example function, but if anyone does, make sure to only use `increment x` rather than `increment(x)`. Actually, try both, get confused, then use that confusion to improve your understanding of how MATLAB handles command/function dual syntaxes :). – Sam Roberts Feb 18 '15 at 11:46
  • @SamRoberts Precisely - I included it just to show that you *could* do this if you really wanted to (even though you shouldn't) and because I feel bad about leaving single line answers :) – Chris Taylor Feb 18 '15 at 11:48
2

Increment / Decrement operators are not implemented in matlab.

There are reasons to keep a language as simple as possible. For c there are long discussions about undefined behaviour using these operators. Mathworks support also pointed out similar reasons not to implement these operators.

Community
  • 1
  • 1
Daniel
  • 36,610
  • 3
  • 36
  • 69