%% One dimensional arrays %% Introduction % % Arrays are useful in a variety of situations, including plotting, storing % tables of numbers, evaluating mathematical expressions and so on. In this % lab, we want to explore ways to create one-dimensional arrays, how to % retrieve particular entries of an array, as well as several useful % functions for operating on one dimenensional arrays. % clear all format short %% Using square brackets % % The simplest way to create an array is to use square brackets to enclose % a list of numbers. % v = [1 3 5 7 9] %% % % or % v = [1.1 -3.4 1.34e2 sqrt(2) 4^5 1/2] %% % % It is often a good idea to use a comma between individual % entries, as in % v = [1.1, -3.4, 1.34e2, sqrt(2), 4^5, 1/2] %% % % so that one can easily distinguish, for example, between % v = [1.1 -3.4] %% % % and % v = [1.1, -3.4] %% % % and not inadvertantly create the scalar value % v = [1.1 - 3.4] %% % % To get help on the use of the square brackets, use the help keyword % punct. %
% >> help paren
% ......
% [ ]  Brackets are used in forming vectors and matrices.
%     [6.9 9.64 SQRT(-1)] is a vector with three elements
%     separated by blanks. [6.9, 9.64, sqrt(-1)] is the same
%     thing. [1+I 2-I 3] and [1 +I 2 -I 3] are not the same.
%     The first has three elements and the second has five.
% .......
% >> help punct
% .......
% ,   Comma.  The comma is used to separate matrix subscripts
%     and arguments to functions.  It is also used to separate
%     statements in multi-statement lines. In this situation,
%     it may be replaced by a semicolon to suppress printing.
 % 
% %% Using the colon operator % % In many situations, we want to create arrays of values that follow a % particular pattern. One very simple pattern is an array of values equally % spaced in some interval. For example, to create an % integer array of the values $1,2,3,...10$, we use the colon % operator and write % v = 1:10 %% % % A more general use % of the colon (:) operator allows us to % specify the step size we wish to take. % v = 0:2:20 %% % % is a list of even numbers between 0 and 20. The step size can also be % negative. For example, % v = 5:-1:-5 %% % % or % v = 50:-5:0 %% % % The colon operator automatically fills in entries in an array with % equally spaced points. However, we can get some unexpected results if the % endpoints we specify are not evenly divided by the stepsize we specify. % Consider the following example % v = 0:3:10 %% % % We notice that the endpoint 10 does not appear in the array. The reason % for this is that 10 is not evenly divided by 3, so is not reached in % steps of 3 starting from 0. Rather than shorten the last step size, % Matlab only includes those values between the specified endpoints that % are even multiples of the step size and shifted by the first endpoint. %

% Carrying the above example further, we see that it is possible to % construct an array that contains only a single element : % v = 10:15:20 %% % % In this case, one step already takes us beyond the specified endpoint, % and so the vector only contains the starting point 10. %

% What happens if the step size does not have the same sign as our end % value minus our start value? In this case, Matlab will create an % empty array. The following example illustrates this. % v = 0:-1:10 %% % % Here, 10-0 is positive, but our stepsize -1 is negative, and so an empty array is created. Any % time we use a step size of 0, we will also get an empty array. The % simplest empty array in Matlab is an empty pair of square brackets ([]). % v = [] %% % % To get help on the colon operator, use the help keyword colon. %
% >> help colon
%  :  Colon.
%     J:K  is the same as [J, J+1, ..., K].
%     J:K  is empty if J > K.
%     J:D:K  is the same as [J, J+D, ..., J+m*D] where m = fix((K-J)/D).
%     J:D:K  is empty if D == 0, if D > 0 and J > K, or if D < 0 and J < K.
% .............
% 
% %% Using the linspace command % % Another way to create equally spaced arrays of points is to use the linspace command. Like the colon operator, linspace takes a starting value and and ending % value for the desired array. But instead of specifying a stepsize, the % linspace command requires the number of % entries in an array. For example, to create a list of integers $1,2,3...,10$ that we did above, we would use % linspace as follows. % v = linspace(1,10,10) %% % % The first argument is the starting value 1, the second % argument is the end value (10), and the third argument is the number of % values in the array. To create a list of integers % $-3,-2,-1,...,5$, use linspace with these arguments. % v = linspace(-3,5,9) %% % % If we change the number of entries in the array, without changing the % starting and ending values, we will effectively change the stepsize. For % example, if we increase the number entries in the above array to 17, we % will get % v = linspace(-3,5,17) %% % % You may be suprised by the fact that we just don't double the number of % entries to cut the stepsize in half. But the stepsize that % we get using linspace is given by the % formula % $$ % \mbox{stepsize} = \frac{\mbox{ending value} - \mbox{starting value}} % {(\mbox{number of values})-1} % $$ %
% For the example above, we have % $\mbox{stepsize} = (5 - (-3))/16 = 0.5$. %

% Because the connection between number of points and step size is not as % apparent when using the linspace command, it % is sometimes easier to specify the number of desired intervals. % Then it becomes obvious how to cut the stepsize by increasing the number % of intervals. % N = 10; % Number of intervals v = linspace(0,1,N+1) % stepsize is (1-0)/N = 0.1 %% v = linspace(0,1,2*N + 1) % Stepsize is (1-0)/(2*N) = 0.05 %% % % One advantage of linspace over the colon % operator is that we can always guarantee that the resulting array will % have the starting and ending values that we specify. As we saw above, % this isn't always true with the colon operator. This advantage becomes % particularly important when we want to use non-integer stepsizes. For % example, one could inadvertantly try % v = 0:0.3333:1 %% % % when what is really meant is % v = linspace(0,1,4) %% % % Both vectors have four entries, but only the second example evenly % divides the interval $[0,1]$ into three % equal sized subintervals. Also, the second vector has exactly 1 in its last % entry, whereas the first vector has 0.9999 in its last entry. %

% The linspace command is widely used in plotting % because as we will see, it is easy to create an array of function values % in a specified interval using linspace. %
%
% >> help linspace
% linspace Linearly spaced vector.
%    linspace(X1, X2) generates a row vector of 100 linearly
%    equally spaced points between X1 and X2.
%  
%    linspace(X1, X2, N) generates N points between X1 and X2.
%    For N = 1, linspace returns X2.
% .............
% 
% %% Column arrays % % One dimensional arrays can be either row or column % arrays. All of the arrays we have computed above are row arrays and have % a single row, and multiple columns. A column array has a single column % and multiple rows. When we used square brackets above, we always created % a row array. % row_array = [1,2,3,4,5] %% % % But we can also use the square brackets to create a column % array. To do this, we use the ; % (semi-colon) operator. % column_array = [1;2;3;4] %% % % Whereas row_array has 1 row and 5 columns, % the vector column_array has 5 rows and 1 column. %
% To create column arrays using the colon operator and linspace, we use the transpose operator, or % ' (apostrophe). This swaps the rows and % columns of the array. For example, % row_array' %% column_array' %% v = (0:5)' %% w = linspace(0,5,6)' %% % % To get help on the the operators above, use the help keyword % punct. %
% >> help punct
% ;   Semicolon.  The semicolon is used inside brackets to indicate
%       the ends of the rows of a matrix.  It is also used after an
%       expression or statement to suppress printing.
% ...........
% '   Transpose.   X' is the complex conjugate transpose of X. 
%       X.' is the non-conjugate transpose.
% ...........
% 
%
% If we are only working with real arrays, we can ignore the fact that % ' is the complex conjugate. % %% Indexing arrays % % Probably the most common use of the colon operator is as a way to % retrieve a range of entries in an array. The entries in an array are % indexed using integers 1,2,3, to N, the length of the array. To retrieve % specific entries, we use the parenthesis operator () with a vector valued argument containing any % valid set of indices. %
% As an example, we create an array of equally spaced values using linspace and retrieve various sets of entries. % v = linspace(-1,1,11) %% % % This array has valid indices 1,2,3, ..., 11. We can retrieve the second % entry in v as % v(2) %% % % We can retrieve multiple elements of an array all at one time by creating % an array of valid index locations. To retrieve every other element in an % array of 7 elements, we use the integer sequence index_set = [1,3,5,7]; v(index_set) %% % % or simply % v([1,3,5,7]) %% % % To construct longer integer sequences, it is natural to use the colon operator % index_set = 1:2:11; v(index_set) %% % % or simply % v(1:2:11) %% % % In both cases, we used an array of integers to specify the desired % indices. We can also use the colon operator to retrieve the entries in % reverse order, % w = v(10:-1:1) %% % % In fact we can choose entries in order, even duplicating entries : % w = v([5 7 2 9 9 3 2 2]) %% % % In Matlab, the first entry in an array is always 1. If we try to index the zero-th element of an % array, we can expect an error %
% v(0)
% 
%
% Subscript indices must either be real positive integers or logicals.
% 
%
%

If we use an index that is larger than the number of elements that we % have, we can also expect an error: %

% v(12)
% 
%
% Index exceeds matrix dimensions.
% 
% %% Special indexing rules % % What if you want to get the last three entries in an array? Since the % length of an array is often one of the variables in the script you are % writing, you might consider doing the following. % n = length(v); v([n-2 n-1 n]) %% % % Here, we used the Matlab length function % to find out how long v is. %

% The above situation arises so often, that Matlab has built into the % language a way to get the last entries of a vector by allowing the use of % the end keyword inside of arrays. This % statement retrieves the last entry in an array % v(end) %% % % To retrieve the last three entries in an array, you can use the end as if it were the actual variable or constant % storing the length of the array. For example, % v([end-2 end-1 end]) %% % % or simply % v(end-2:end) %% % % The colon operator by itself in an array changes the shape of the array % from a row vector to a column vector. % v(:) %% % % Example

% Suppose we want to compute the midpoint between successive locations % along a straight line. We could do the following : % x = [0.1 4.3 5.6 10.9 13.5 16.7 21.9] % Locations along a line (feet) %% midpt = (x(1:end-1) + x(2:end))/2 % Midpoint between each pair of points. %% Simple array concatenation % % We can always construct a new array by gluing two arrays together. For % example, suppose we have two row vectors u and % v. We can construct a new array w by glueing, or concatenating u and v together using square % brackets. % u = -5:-2 %% v = 21:27 %% w1 = [u v] %% w2 = [v u] %% % % The resulting arrays w1 and w2 each have length equal to the sums of the lengths % of u and v. %
% We can concatenate column arrays as well. In this case, we can stack % arrays on top of each other using the semi-colon operator. % x = [1;1;1;1]; y = [2;2;2;2]; z = [x;y] %% % % In a later lab, we will see that it is possible to concatenate column % arrays horizontally, or row arrays vertically to obtain two dimensional % arrays. Here a preview of what is to come. % A = [x y] %% Array functions for one-dimensional arrays % % Matlab has several functions which operate on one-dimensional arrays. We % have already see one such function, the length function, which returns the number of % elements in the array. % x = 0:25:1000; length(x) %% % % or % x = linspace(0,1000,35); length(x) %% % % Many Matlab functions are convenient in that they allow us to avoid the % use of the loops that are often required in other languages. A partial % list of such functions include min, max, sum, prod, cumsum, cumprod, mean, median, std and sort. % v = 1:10; %% % % We can compute the minimum and maximum values of an array using the % min and max % functions. % min(v) %% max(v) %% % % To sum up all the entries in an array, or to muliply all the entries % together, use sum and prod. % sum(v) %% prod(v) %% % % The cumulative sum or product of an array x % is a second array y whose % $n^{th}$ entry is the sum or product of the % first n entries of x. The Matlab commands used % to produce this array y are % cumsum and prodsum. % cumsum(v) %% cumprod(v) %% % % In many situations, we want to compute the difference of successive % entries of an array. For example, suppose we had an array of % locations along a straight line segment and we want to compute the % distance between the locations. The diff comes % in handy for this. % x = [1.1 4.5 9.1 11.4 21.7] % locations along a straight line, in feet. %% diff(x) % distance between each successive location %% Creating arrays of zeros, ones and random numbers. % % We can create arrays of constant values in one of several ways. For % example, to create an array of all zeros or all ones, we use the commands % zeros or ones. % v = zeros(1,5) %% w = ones(1,5) %% % % To then create an array of all 7s for example, we can either add 7 to % an array of all zeros, or multiply an array of all ones by 7. % v = 7 + zeros(1,5) %% u = 7*ones(1,5) %% % % In each the above examples, we passed two arguments to the zeros or ones commands. % These commands indicate how many rows and columns each resulting array % should have. Here, we created only row or column vectors, but as we % will see later, we could just have easily created a two dimensional array % w = ones(3,5) %% % % In many situations, it is useful to have an array of random % numbers. To do this, we can use the rand % command, which creates an array of random numbers uniformly distributed % in the interval [0,1]. % format short e x = rand(1,10) %% % % This creates a row vector (i.e. has only 1 row) with 10 entries (i. e. 10 % columns) of random numbers. %
%
% >> help rand
%  rand Uniformly distributed pseudorandom numbers.
%     R = rand(N) returns an N-by-N matrix containing pseudorandom values drawn
%     from the standard uniform distribution on the open interval(0,1).  rand(M,N)
%     or rand([M,N]) returns an M-by-N matrix.  rand(M,N,P,...) or
%     rand([M,N,P,...]) returns an M-by-N-by-P-by-... array.  rand returns a
%     scalar.  rand(SIZE(A)) returns an array the same size as A.
% ............
% 
% %% Elementary statistical functions % % In this section, we will use array functions that take as input random % arrays of numbers. % x = rand(1,100); %% % % The mean, median, standard deviation and variance of an array of numbers % can be computed using the mean, median, std and var functions. % mean(x) %% median(x) %% std(x) %% var(x) %% % % For large enough samples, we expect the mean and median of random % integers generated using rand to tend towards % 0.5, while the standard deviation tends towards % $1/\sqrt{12}$
and variance tends towards % $1/12$ % format long; x = rand(1e8,1); %% mean(x) %% median(x) %% std(x) 1/sqrt(12) %% var(x) 1/12 %% Sorting values in an array % % We can sort the entries in an array using the sort command. % x = rand(100,1); x_sorted = sort(x); %% % % To see that we really have a sorted % list, we can compare the first entry of x_sorted to % the minimum value of x, and the last entry of % x_sorted to the maximum value of x. % x_sorted(1) min(x) %% x_sorted(end) max(x) %% % % We can use sort to compute the median of a set % of numbers. If our array has an odd number of values, the median will be % the entry $(n+1)/2$ in the sorted % array of length n. % x = rand(101,1); x_sorted = sort(x); x_sorted(51) % Median value : half are below this value; half are above %% % % This is exactly the value reported by median % median(x) %% % % For an even number of values, the median is computed as the average of % the two middle values in a sorted array. % x = rand(100,1); x_sorted = sort(x); (x_sorted(50) + x_sorted(51))/2 %% median(x) %% Lab exercises % %
% Use the Matlab functions % min, % max, % sum, % prod, % cumsum, % cumprod, % mean, % median and % std % to compute the value of the indicated expressions below. % To start, first create an array $x$ of 100 random values using the rand function. For example, %
%
% x = rand(100,1);
% 
% You will use this array for each of the exercises. %

%
    %
  1. % $\displaystyle{\sum_{k=1}^{n} x_k}$
  2. %
  3. % $\displaystyle{\min_{1 \le k \le n} x_k}$
  4. %
  5. % $\displaystyle{\frac{1}{n}\sum_{k=1}^n {x_k}}$
  6. %
  7. $\displaystyle{n}$ %
  8. % $\displaystyle{y_j = \prod_{k=1}^j {x_k}}$, % for $j = 1,2,...,n$
  9. %
  10. % $\displaystyle{\max_{1 \le k \le n} x_k}$
  11. %
  12. % $\displaystyle{\sqrt{\frac{1}{n-1}\sum_{k=1}^n (x_k - \mu)^2}}$, % where $\displaystyle{\mu = \frac{1}{n}\sum_{k=1}^n % x_k}$
  13. %
  14. Find the value $\sigma$ % in $x$ such % that half of the values $x_k$ are % less than $\sigma$ and half are % greater than $\sigma$.
  15. %
  16. % $\displaystyle{y_j = \sum_{k=1}^j {x_k}}$ % for $j = 1,2,...,n$
  17. %
  18. % $\displaystyle{\prod_{k=1}^{n} x_k}$
  19. % %
%
%
    %
  1. You are planning a bicycle trip along a 400 mile stretch of % a very straight midwestern rural highway and plan to stop each night % at a different town. The towns are irregularly spaced, but you have % mileage markers for each town, given in the array M : %

    % $ % M = [0, 27, 69, 101, 120, 154, 178, 211, 235, 278, 306, 327, 356, 391, 400] % $ %

    % You would like to compute the distances you have to travel each day, as % well as other statistics about your trip. %

    % To start, create an array M containing the mile % markers above, and a second array D containing % the distances between each of the mile markers and answer the following % questions. %

    %
      %
    1. What is the shortest distance you will have to bicycle on % any day?
    2. %
    3. What is the longest distance?
    4. %
    5. What is your average daily distance?
    6. %
    7. How far will you have to go on day 7?
    8. %
    9. If you would like to stop each day for lunch at exactly % the halfway point for each day's journey, what mileage values should you % plug into your GPS to assure that you do not miss lunch?
    10. %
    11. How can you recover your array M from your array D?
    12. %
    % For these problems, you will want to use diff, % mean, min, max and cumsum. %
% %% % %

Compare your answers with the solutions.

%