Skip to main content

4.9) Arithmetic On Arrays


We can also perform arithmetic between arrays and scalars.

[matlab]
>> a=[0.8:0.4:2.8]
a= 0.8 1.2 1.6 2.0 2.4 2.8
[/matlab]

Let's add 2 to every element of vector "a".

[matlab]
>> b=a+2
b= 2.8 3.2 3.6 4.0 4.4 4.8
[/matlab]

Let's subtract 1 from vector "a".

[matlab]
>> c=a-1
c= -0.2 0.2 0.6 1.0 1.4 1.8
[/matlab]

Let's now multiply vector "a" by 1.2

[matlab]
>> d=a*1.2
d= 0.96 1.44 1.92 2.40 2.88 3.36
[/matlab]

Finally let's divide vector "a" by 1.4

[matlab]
>> e=a/1.4
e= 0.5714 0.8571 1.4286 1.7143 2.00
[/matlab]

We can do arithmetic on single elements.

[matlab]
>> f=a(1)+2;
f=2.8
[/matlab]

We can also just do arithmetic on sets of elements.

[matlab]
>> g=a(1:4)+2
g= 2.8 3.2 3.6 4.0
[/matlab]