Download presentation
Presentation is loading. Please wait.
1
Matrix Mayhem: Outline
Logical operations Special numbers Using functions Generating matrices (aka arrays) Matrix indexing Matrix arithmetic Plotting 201 Some basic handle graphics Another “real world” example Some Language Basics Using Matrices More Plotting
2
Logical Operations Logical operations tests if something is true (1) or false (0). In Matlab, they usually work on arrays: 1:10 > 8 Some other less obvious logical operations: a = 1:10; a == 3 % Tests equality a ~= 3 % Tests for not equal ~(a > 8) % not greater than 8 (a > 6) | (a < 2) % First or second (a > 6) & (a < 2) % 1st and 2nd In Matlab, it is often useful to assign the results of a logical operation to a variable: b = mod(a,2) == 0 % Tests for even nums Many functions return logicals: any, all, isnan, isempty (e.g. see MM7 pg. 194).
3
Special Numbers There are some special numbers in matlab:
NaN, inf, -inf eps, realmax, realmin pi, e NaN stands for “not a number” and is used for missing data. Basic arithmetic does not work with NaN. NaN + 1 [1,NaN,2] == NaN % Answer: [0,0,0] isnan( [1,NaN,2] ) % Answer: [0,1,0] Use isnan to check for NaN. inf, -inf = plus, minus infinity. Some math works. 1e25 < inf 1/inf eps is a very small number – relative accuracy
4
Using Functions Matlab functions often accept different types of inputs and can output more than one variable. Using a function that returns a single argument: log(1:10) b = log(1:10); Using a function that returns multiple outputs: a = randn(5,3) % normal random nums. [b,I] = min(a) % Use [] for mult. args. [c,J] = min(a,[],2) % Min of each row Matlab functions often change how they work based on the num. & type of inputs and the num. of outputs. First output of a function can be used as input to another function: sum( min( rand( 5, 3 ) ) )
5
Understanding help information:
One-line description. Name always in Caps. help min MIN Smallest component. For vectors, MIN(X) is the smallest element in X. For matrices, MIN(X) is a row vector containing the minimum element from each column. For N-D arrays, MIN(X) operates along the first non-singleton dimension [Y,I] = MIN(X) returns the indices of the minimum values in vector I. If the values along the first non-singleton dimension contain more than one minimal element, the index of the first one is returned MIN(X,Y) returns an array the same size as X and Y with the smallest elements taken from X or Y. Either one can be a scalar [Y,I] = MIN(X,[],DIM) operates along the dimension DIM When complex, the magnitude MIN(ABS(X)) is used, and the angle ANGLE(X) is ignored. NaN's are ignored when computing the minimum Example: If X = [ then min(X,[],1) is [2 3 4], ] See also MAX, MEDIAN, MEAN, SORT. Primary usage. Secondary usage. More or different inputs. Related functions
6
Generating Matrices (aka Arrays)
By hand: a = [ 1, 45, 3; 2, 3.45, 8 ] Using a function to generate a matrix: b = zeros( 3, 4 ) c = ones( 2, 3, 2 ) % 3D array avar = 1:0.05:3 % The colon function d = rand(2) % rand nums between 0 and 1 By repetition: a = repmat( 1:3, [2,2] ) By reference (i.e. matlab automatically creates): myvar(3,4) = 21 Arrays tend to grow in matlab all by themselves: a = ones(2,3); a(end+1,end+2) = pi Matlab will fill in missing elements with zeros.
7
Matrix indexing Single element: Multiple rows or columns:
a = reshape(1:20,4,[]); a(2,3) Multiple rows or columns: a(:,end-1:end) a([1,3,4],2:3) Multi. dimensional arrays can be treated as vectors: a(3) a(end) b = a(:) % Array into column vector Using a logical index array (this is really useful!): b = a >= 10 a(b) = NaN
8
More Matrix Stuff The empty matrix:
isempty(a) % Tests for being empty size(a) % Gives dimensions of a Matrices can be joined if they have the correct size: a = 10:20; b = a.^2 c = [a, b] % Not really what we want d = [a; b] % That's better Eliminating rows or columns: d( :, 5:6 ) = [] d( 1, : ) = [] Matrix transpose: a = reshape( 1:20, 4, [] ); b = a' % ' is for transpose
9
Matrix Arithmetic Addition and subtraction work as expected:
a = reshape(1:20,4,[]); a + a All other operations usually come in two varieties: with and without the dot (.). With the dot, the operation is on each element: a .* a a ./ a a .^ (1/3) % Elements to the 1/3 power Without the dot, operation is linear algebra: a * a' Either works when one part is a single number: a * pi a .* pi
10
More Matrix Arithmetic
Usually, you want to do element-by-element operations. Example – length of a set of vectors: axis([0,1,0,1]), title('Click 5 times') [x,y] = ginput(5); plot(x,y,'ok') r = sqrt( x.^2 + y.^2 ) % Compute length Linear algebra useful for modeling. Example – Leslie Matrix of population growth: s = 0.9; % Survival L = s * diag(ones(1,5),-1); % 6 ages L(end,end) = s; % Last age a plus class L(1,2:end) = 1; % eggs – age 2 mature Use linear algebra to follow population: N0 = [1;0;0;0;0] % Initial population N2 = L * L * N0; N5 = L^5 * N0;
11
Leslie Matrix Explained
The previous Leslie Matrix looked at follows: L / / / / /10 9/10 Blue: Reproduction (age independent in this case after maturity). Red: Aging and mortality Green: Would be used for stage structured populations.
12
Plotting 201 Some other useful plotting functions (look at each individually): a = 0:0.1:3; semilogy( a, exp(a) ) bar(a,exp(a)) hist(randn(1,10000),30) % 30 bars How to change the axis size: xl = xlim % Get current x-axis limits xlim([0,5])% Set new axis limits values Same for ylim and zlim. See also axis. Some other useful functions: grid on box off axis tight close % Close figure window
13
Basic Handle Graphics Almost all plotting functions return “handles”: numbers that reference something plotted. a = 0:0.5:3; fig_hdl = figure; bar_hdl = bar(a,exp(a),0.5); hold on plot_hdl = plot( a, exp(a) ); hold off Handles can be used to get and set properties of a plot with get and set functions: set(fig_hdl,'color','g') set(bar_hdl,'facecolor','r') set(plot_hdl,'linewidth',2,'marker','o') get(plot_hdl,'color') gcf and gca are handles for current fig. and axis. get(gca) % get of hdl shows all values set(gca,'ydir','reverse')
14
Real World Example: PVA
PVA is population viability analysis. Refers to determining persistence of a population. I want you to do several things with a Leslie matrix for the spotted owl stored in: z:\Pkg\WFCB\class2\spotted_owl_Leslie_matrix.txt Load the Leslie matrix and take a look. Starting with an initial population of 1 age-1 individual, show me the population at time steps 0, 1, 5, 10, and 20. Hint: use the bar function to plot it. Test the persistence of owl populations for a number of initial conditions by looking at the population after many time steps. Hint: the rand function can generate your initial populations Get the eigenvalues of the Leslie matrix. What does this say about population persistence?
15
Solution to Real World Example
A solution to the exercises is in: z:\Pkg\WFCB\class2\class2_PVA_solution.m cd z:\Pkg\WFCB\class2\ edit class2_PVA_solution.m class2_PVA_solution
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.