Skip to main content

4.7) A Final Use of The Colon Operator


Another use of the colon operator is to compress an array down to a vector. This is useful if you want to use a reduction type operator on a whole array. For example:

  • Use mean to calculate the mean of an array
  • Use std to calculate the standard deviation of an array
  • Use min or max to calculate the min/max of an array.

What do we mean by a reduction type operator? These operators work on column or row vectors and generate a single output value. So how can we find the average value of an array?

[matlab]
a=rand(100,100);
b=mean(a);
size(b);
ans= 1 x 100
[/matlab]

We end up with a row vector where each cell is the mean of a column of "a". So we could then do:

[matlab]
a=rand(100,100);
b=mean(a);
c=mean(b);
size(c);
ans= 1 x 1
[/matlab]

"c" is now the mean of the row vector "b". But we can do this more simply using the colon:

[matlab]
a=rand(100,100);
b=mean( a(:) );
size(b)
ans= 1 x 1
[/matlab]

Here the colon operator compresses the array "a" into a vector so that "mean( a(:) )" results in a scalar value.