GEOSC 444
Matlab Application for Geoscience

Lesson 2: More efficient vector creation

PrintPrint

Syntax introduced:

: linspace logspace

Doing it by hand is okay . . . once

Up until now we created vectors by entering each element of the vector by hand. This was okay at the time because all of our vectors were small. Most Earth science datasets and model runs, on the other hand, are large and have a lot of datapoints, and there's no way you want to be typing in values by hand. Commonly, you want a regularly spaced array in which you specify the increment or else you specify the number of data points you want and let MATLAB set the increment.

Create a vector with constant spacing

Way 1:  specify the spacing

To create a vector with spacing specified you can use the : operator and type beginningNumber : increment : endNumber. The default if you don’t specify an increment is to increment by 1. You can also use fractional numbers and negative numbers with this technique.

Way 2: specify the number of elements

Another way to create a vector with constant spacing is to use linspace and set the vector with linspace(beginningNumber , endNumber, numberOfElements). If you don’t specify the number of elements, the default is 100. MATLAB will figure out the spacing for you.

You can also create vectors with regular logarithmic spacing instead of linear spacing. In this case you use logspace and type logspace(beginningExponent, endExponent, numberOfElements). The default here is 100 elements as well.

Let's say I want to make a vector that goes from 10 to 20 by ones. We know several ways to do this by now. Here are a few:

>> x=10:1:20 
  x =     10    11    12    13    14    15    16    17    18    19    20
 
>> x=10:20 
  x =     10    11    12    13    14    15    16    17    18    19    20
 
>> x=linspace(10,20,11) 
  x =     10    11    12    13    14    15    16    17    18    19    20
 
>> x=(0:10)+10 
  x =     10    11    12    13    14    15    16    17    18    19    20
 
>> a=10:15; 
>> b=16:20; 
>> x=[a b] 
  x =     10    11    12    13    14    15    16    17    18    19    20

There's lots of ways to skin this cat.