MATLAB

4. Arrays

Constructing Arrays

We will illustrate four somewhat different ways of constructing a simple array of numbers. The whole array is represented by a variable name along similar lines to scalar variables. For example, a, x, Y, A3, Xarray are suitable names for arrays providing they have not already been used for another purpose. The first method of constructing an array is merely to list the numbers in the array, enclosed inside square brackets and divided either by spaces or commas. Type in the following after the prompt:

x=[3, -5.1, 0, 6, 11, -17, pi]

y=[8 2 -12 3/4 1.234567 1 10]

This is fine if you have only a few numbers to input into an array (seven in each of the above two examples). However, if there are hundreds, we need another method. This is possible if the numbers in the array are equally spaced. We use the colon notation. Type in the following after the prompt:

A=[-3:21]

B=[3.33:12]

Clearly [a:b] is an array starting at a with increments of one until we reach b but not going beyond b. If a and b are integers with a < b, the number of elements in the array is b − a + 1. Why?

Suppose we want an array to extend over the interval from a to b with n equal subintervals of length h. Then clearly h = b − a/n and the number of elements in the array will be n + 1. Why?

For example, suppose you wanted an array of values from 2.5 to 4.0 with 25 subintervals, which implies that the values need to be incremented by a step-size of h = 0.06. Why? The number of values in the array will be 26. Show that the following three expressions are equivalent by entering each expression (Matlab command only) after the prompt:

 

C=[2.5:0.06:4.0] [a:h:b] is an array from a to b with step-size h.

C=linspace(2.5,4.0,26) linspace(a,b,n+1) is an array from a to b with n subintervals, n + 1 points (avoids having to find h).

C=2.5 + 1.5*[0:0.04:1] divides the interval from 0 to 1 into 25 equal subintervals of length 0.04 and then scales & shifts.

Which of the above do you prefer?

Of course, when you have an array with a large number of elements you should follow statements like those above with a semi-colon “;” to avoid printing lines of probably unwanted numbers in your output.

Example 1:

An array from −2π to 2π using 150 subintervals is

array1=linspace(-2*pi,2*pi,151);

Example 2:

An array from 3 to 76 with steps of 0.5 is

array2=[3:0.5:76];

Exercise: Suppose we need an array (in hours) to represent the 24 hours of a day, from midnight to midnight, and we want to have time-steps of one minute. Then a suitable array might be:

day=[0 : 1/60 : 24];

What equivalent statement uses the linspace command?

You can append the elements of one array to the end of another array. Enter the following:

clear all

x1=[1 6 -7]

x2=[5 9 0 -1 11]

x=[x1 x2]