Skip to main content

4.6) More on the Colon Operator


  • You may want to create a vector with a known start and end value but with a specific number of samples in between. How would you achieve that?

Let's divide the interval between 0 and pi into 10 equally spaced samples.
[matlab]
>> nsamples=10
>> stride=pi/(nsamples-1)
>> pi_vector=(0 : stride : pi)
>>
[/matlab]

  • Alternatively we could have used the Matlab function "linspace":

[matlab]
>> pi_vector=linspace(0,pi,10)
>>
[/matlab]

  • We can also create matrices using these concepts. To create a 3x3 matrix, of the numbers 1 to 9, we could use square brackets:

[matlab]
>> d=[1 2 3 ; 4 5 6 ; 7 8 9];
[/matlab]

Note that we used the semi-colon within the square brackets. The semi-colon is used to separate rows in the matrix. We could have alternatively used colons too:
[matlab]
>> e=[1:3 ; 4:6 ; 7:9];
[/matlab]