Compound Assignments

In the expression
A = A + 3;
the variable name A appears twice. The expression reads ``add 3 to A'', and can be written in a condensed form
A += 3;
Note that in A += B, A must be a variable or lvalue, while B can be any expression. A += B is a valid statement as long as A + B is defined. For example
>> x = 35;
>> y = 6;
>> x += y + 1;
>> x
    42
>> A = [3, 5, 9];
>> B = [2, 0, -2];
>> A += B .^ 2;
>> A
    7   5   13

There are compound assignment operators for other arithmetic operators, defined in the same way. They are listed in Table (4.1).

Table 4.1: Table of Compound Assignment Operators
Operation Equivalent
A += B A = A + B
A -= B A = A - B
A *= B A = A * B
A /= B A = A / B
A %= B A = A % B
A \= B A = A \ B
A ^= B A = A ^ B
A .*= B A = A .* B
A ./= B A = A ./ B
A .^= B A = A .^ B

oz 2009-12-22