
Syntax introduced:
mean median mode sum :
Arithmetic with vectors
Any arithmetic you perform on a vector with a scalar is by default performed piecewise on each vector element. For the following examples, I'm going to create a vector x and use it to demonstrate what I mean. You should open up MATLAB and follow along to verify my examples for yourself. First let's create x and then multiply it by 2.
>> x=[1 3 5 9 15]; >> x*2 ans = 2 6 10 18 30 >> x x = 1 3 5 9 15
What is the most important thing to notice about this sequence of commands? The actual value of x didn't change even though we multiplied it by 2. Huh! Is that counterintuitive? Maybe. Think of it this way. You asked MATLAB what the answer would be if you multiplied x by 2 and it told you. If you actually want to set x equal to a new value you have to use = for assignment, like so:
>> x=[1 3 5 9 15]; >> x=x*2 x = 2 6 10 18 30Now you have overwritten the original value of x. Maybe you want to keep the old value of x. That's fine. Just assign a new variable to the product of x and 2, like so:
>> x=[1 3 5 9 15]; >> doubleX=x*2 doubleX = 2 6 10 18 30 >> x x = 1 3 5 9 15
Addition, subtraction and division all work the same way as multiplication. I'm going to repeat what I said before because it will be important later: These element-by-element operations work like they do because in our examples, we have a one-dimensional vector, x, and a scalar. Arrays and array operations (when x has more dimensions or there isn't a scalar) will be discussed later.
Standard simple statistical calculations such as mean, median, mode, and sum are all performed over the entire vector x unless you tell MATLAB to use a subset of the vector. Use the : to specify a range within a vector.
>> x=[1 3 5 9 15]; >> x(1:3) ans = 1 3 5 >> mean(x(3:5)) ans = 9.6667
In the snippet above I asked MATLAB for the first three elements of x. Then I asked MATLAB to take the mean of the 3rd through 5th elements in x.