570 likes | 769 Views
Advanced MATLAB. Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions. Using an Index to Address Elements of an Array. In the C/C++ programming language, an index starts at 0 and elements of an array are addressed with square brackets [∙] :
E N D
Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions
Using an Index to Address Elements of an Array In the C/C++ programming language, an index starts at 0 and elements of an array are addressed with square brackets [∙]: 8 2 -3 7 -1 x[0] x[1] x[2] x[3] x[4] ↑ ↑ ↑ ↑ ↑ In MATLAB, an index starts at 1 and elements of an array are addressed with parentheses (∙): 8 2 -3 7 -1 x(1) x(2) x(3) x(4) x(5) ↑ ↑ ↑ ↑ ↑
Columns, Rows, and Pages for a 2-Dimensional Array (Matrix) x(m,n) m is the row number n is the column number x(m,n)is the element of the matrix x that is: in the mth row in the nthcolumn
Columns, Rows, and Pages for a 3-Dimensional Array x(m,n,p) m is the row number n is the column number p is the page number x(m,n,p) is the element of the 3-dimensional array x that is: in the mth row in the nth column on the pth page
% scalars, vectors, matrices, 3-dimensional arrays a1 = zeros(1,1); % scalar disp(['a1: ',num2str(size(a1))]) a2 = zeros(1,4); % vector disp(['a2: ',num2str(size(a2))]) disp(a2) a3 = zeros(2,2); % matrix disp(['a3: ',num2str(size(a3))]) disp(a3) a4 = zeros(2,2,3); % 3-dimensional array disp(['a4: ',num2str(size(a4))]) a1: 1 1 a2: 1 4 0 0 0 0 a3: 2 2 0 0 0 0 a4: 2 2 3
% Editing arrays with parentheses () B = [1 2 3 4; 5 6 7 8]; disp('before:') disp(B) b = [0 0]'; B(:,4) = b; disp('after:') disp(B) before: 1 2 3 4 5 6 7 8 after: 1 2 3 0 5 6 7 0
Exercises Create a matrix of zeros with 3 rows and 4 columns. Create a matrix with 2 rows and 2 columns, with all elements equal to 5. Insert the smaller matrix into the lower right-hand corner of the larger matrix. Hints: zeros()5*ones()
% array versus matrix multiplication a = [1 2; 3 4]; disp(a*a) % matrix multiplication disp(a.*a) % array multiplication 7 10 15 22 1 4 9 16
% array multiplication, division, and power x = [1 4; 9 8]; y = [1 2; 3 4]; disp(x.*y) % array multiplication: .* disp(x./y) % array division: ./ disp(x.^2) % array power: .^ 1 8 27 32 1 2 3 2 1 16 81 64
MATLAB Documentation for fprintf fprintf Write data to text file Syntax fprintf(fileID,formatSpec,A1,...,An) My comments: fileID not used when printing to Command Window formatSpec enclosed in single quote marks: ‘string’ A1,…,Anare variables (or numbers) to be printed
% print pi to 7 decimal places fprintf('%9.7f\n',pi) % f fixed-point number % a.b field width = a characters % b digits to the right of decimal point % \n newline 3.1415927
% print a column of numbers x = [1.34, -2.45, 0.91]; fprintf('%5.2f\n',x) % There can be 2 characters on left. 1.34 -2.45 0.91
Exercise Print as a fixed-point number to 12 decimal places.
% print signed integers with field width 4 x = [198, -230, 3]; fprintf('%4d\n',x) 198 -230 3
Exercise Create a vector containing the (integer) elements: 0,-1,2,-3. Print these numbers in a column with right justification.
Cell Arrays A cell array can combine different data having different data types all in one array. A cell within a cell array is referenced by an index. A cell array is frequently an input argument of a function. This permits a collection of data (even of different data types) to be input to the function using a single argument.
% create a cell array using braces {} y = {'scores',[73,38,81,55]}; y{3} = 'success'; celldisp(y) y{1} = scores y{2} = 73 38 81 55 y{3} = success
% What is in the second cell of the cell array y? disp(y(2)) [1x4 double]
% What values are in the second cell of the cell array y? disp(y{2}) 73 38 81 55
% print values in the cell array y fprintf('%s: ',y{1}) fprintf('%2d ',y{2}) fprintf('\n') scores: 73 38 81 55
% create a cell array using the function cell() x = cell(1,2); x{1} = 'salary'; x{2} = 45000; celldisp(x) x{1} = salary x{2} = 45000
Structures A structure can combine different data having different data types under one banner. Each component of a structure is called a field. A structure array is an array, each element of which is a structure, and all structures in the structure array have the same set of fields.
% simple structure a.label = 'x'; a.vect = 0:5; disp(a) label: 'x' vect: [0 1 2 3 4 5]
% create structure array using function struct() c = struct('label',{'x','y'},'vect',{0:5,0:10}); disp(c) disp(c(1)) disp(c(2)) 1x2 struct array with fields: label vect label: 'x' vect: [0 1 2 3 4 5] label: 'y' vect: [0 1 2 3 4 5 6 7 8 9 10]
% create 1 x 2 structure array c = struct('class',{71,72},'language',{'C','MATLAB'}); for n = 1:2 fprintf('ECE %2d: %s\n',c(n).class,c(n).language) end ECE 71: C ECE 72: MATLAB
% structure array b(1).label = 'x'; b(2).label = 'y'; b(1).vect = 0:5; b(2).vect = 0:10; disp(b) disp(b(1)) disp(b(2)) 1x2 struct array with fields: label vect label: 'x' vect: [0 1 2 3 4 5] label: 'y' vect: [0 1 2 3 4 5 6 7 8 9 10]
Flow of Control Redirection if else elseif Loops for
% if for k = 0:3 if k == 2 disp(k) end end 2
% if and else for k = 0:3 if k >= 2 disp(k) else disp([num2str(k),' < 2']) end end 0 < 2 1 < 2 2 3
% elseif for k = 0:3 if k < 2 disp([num2str(k),' < 2']) elseif k == 2 disp(k) else disp([num2str(k),' > 2']) end end 0 < 2 1 < 2 2 3 > 2
% or for k = 0:4 if k < 2 || k > 3 disp(k) end end 0 1 4
% and (input number is 3) x = input('number: '); if x >= 1 && x <= 5 disp('between 1 and 5') end between 1 and 5
Exercise Create a script that does the following:
% Compare 2 methods of printing a vector tic for k = 0:9 % within this loop, k is a scalar fprintf('%1d ',k) end fprintf('\n') toc tic m = 0:9; fprintf('%1d ',m) % This is preferred. It is faster. fprintf('\n') toc 0 1 2 3 4 5 6 7 8 9 Elapsed time is 0.000264 seconds. 0 1 2 3 4 5 6 7 8 9 Elapsed time is 0.000077 seconds.
% Add all even integers 0 through 100 x = 0; for m = 2:2:100 % even integers, 2 through 100 x = x + m; end fprintf('%4d\n',x) 2550
Exercise Calculate the sum of all odd integers from 1 through 101.
Vectorization Preallocation of memory Vectorizing Loops
% Preallocation of memory tic % SLOW: frequent lengthening of x x(1) = 1; x(2) = 1; for n = 3:100000 x(n) = x(n-1)*x(n-2); end toc tic % FAST: preallocation of memory for x y = ones(1,100000); for n = 3:10000 y(n) = y(n-1)*y(n-2); end toc Elapsed time is 0.526046 seconds. Elapsed time is 0.021451 seconds.
% Vectorizing a loop: linspace tic % slow phi = 0; dphi = 2*pi/100; g = zeros(1,1001); for n = 1:1001 g(n) = sin(phi); phi = phi + dphi; end toc tic % fast phi = linspace(0,20*pi,1001); h = sin(phi); toc Elapsed time is 0.002522 seconds. Elapsed time is 0.000136 seconds.
Exercise Here is one way to generate samples of a sinewave: for n = 1:8 x(n) = sin(pi*(n-1)/4); end Enter the above code and display the results. Then vectorize this code and verify that your vectorized code gives the same results.
Functions Function m-file Local variables Functions with multiple inputs/outputs
function v = sphereVol(r) % calculates the volume of a sphere % input r = radius % output v = volume c = 4/3; v = c*pi*(r^3); end % sphereVol
Local Variables Variables appearing in a function are local. These local variables do not appear in the MATLAB workspace and are not visible outside of the function in which they occur. For example, a variable c in the MATLAB workspace will be unaffected by a (local) variable c that appears within a function. Within the function, the local cis recognized and the workspace cis not. When the function returns, the local cis forgotten and the workspace cis again recognized. The input arguments of a function have local names. When the function returns, these local names are forgotten. The output variables of a function have local names. The values of these output variables are returned to the caller; however, the local names of these output variables are forgotten.