next up previous
Next: Displaying output Up: MATLAB summary Previous: Mathematical functionscos, sin

Arithmetic operators


The commonly encountered arithmetic operators are:
    plus                   - Plus                               +    
    minus                  - Minus                              -    
    mldivide or mrdivide   - Left or right matrix divide       \ /  
    mtimes                 - Matrix multiply                    * 
    mpower                 - Matrix power i.e. exponentiation   ^
and these operators can also be used with scalars, which are regarded as tex2html_wrap_inline166 matrices, as has been indicated above. The order of evaluation is brackets, followed by exponentiation, then * or / and finally + or -, i.e. as normal. Thus we find
>> 2-(2^3-8/4)*3
ans =
     -16

The operators tex2html_wrap_inline168 and / have special meaning when used with matrices. In particular

>> a=[2 0; 0 2]
a =
     2     0
     0     2
>> b=[1;1]
b =
     1
     1

>> x=a\b
x =
    0.5000
    0.5000
>>
i.e. the MATLAB form x=a tex2html_wrap_inline168 b gives the same result as tex2html_wrap_inline172 , but more efficiently, since Gaussian elimination is used. However, the following also works:
>> x=inv(a)*b
x =
    0.5000
    0.5000
>>
Although MATLAB was originally designed for matrix manipulations, it is often useful to be able to perform element by element multiplication, division or exponentiation. There are three special operators that allow this, namely .* which is the times operator, ./ which is the right array divide and .^ which is the array power operator. They are used in the following way:

vec4=vec1.*vec2: vec4(i)=vec1(i)*vec2(i), i=1,2,...,n

vec5=vec1./vec2: vec5(i)=vec1(i)/vec2(i), i=1,2,...,n

vec5=vec1.^2: vec5(i)=vec1(i)^2, i=1,2,...,n Here are some examples:

>> x=[-pi 0 pi]
x =
   -3.1416         0    3.1416
>> x.^2
ans =
    9.8696         0    9.8696
>> y = x .* cos(x)
y =
    3.1416         0   -3.1416
>> z = (1+sin(x)) ./ cos(x)
z =
   -1.0000    1.0000   -1.0000
Study these examples carefully, as the three operators are very useful when working with vectors.


Charlie Macaskill
Fri Mar 5 16:05:28 EST 1999

Copyright © University of Sydney 2003