MATLAB Basic Exercises Arrays Intro Access single elements Access element blocks Use another array to extract elements Matrix construction Matrix orientation: Scalar Matrix operations, Standard Arrays, Replication, Array manipulation, Subsets access, reshape, throw away row, duplicate row, subscripts, Cell Arrays, Structure generation, Dynamic addressing, Structure Functions Handles and Functions Handle to Anonymous function Handle to named function Symbolic Nested function Information on a function handle for a given function function handle from function name string Function name string to function handle ISA FFT Marker on peak
Symbolic: differentiation, Bessel functions 1 st kind, Jacobian, Limits, Integration, pareto tail example to construct piecewise distributions Integration with Real parameters Summation Taylor series Function definitions Max Min Inflections Zeros Conv
A Few cheesy test Questions
warm up games: http://www.gutenberg.org/files/27635/27635-h/27635-h.htm www.chess.com/play/computer Simon Says online Sudokus
ones(3);size(g);ones(size(g));eye(4);eye(2,4) % STANDARD ARRAYS eye(4,2);rand(3);rand(1,5);b=eye(3);rand(size(b)) randn(2) % NORMAL zero mean, unit variance randn(2,5)
a=1:4;diag(a);diag(a,1);diag(a,-2)
d=pi;d*ones(3,4);d+zeros(3,4);d(ones(3,4))
repmat(d,3,4) % replicate matrix, D matrix, d scalar D(r*c)=d % row vector r*c-th element is d D(:)=d % fill all out with d D=reshape(D,r,c)
A=[1 2 3;4 5 6;7 8 9] % ARRAY MANIPULATION
A(3,3)=0;A(2,6)=1 A(:,4)=4 % 4th column all to value 4 A(:,4)=[4;4;4] % same as previous A(:,4)=[4 4 4] % ain't work
% simultaneous data extraction from structure arrays % build reception container first a=ones(2,3); b=zeros(2,1); c=(3:4)'; d=[a b c]; d=cat(2,a,b,c) [m,n]=size(d);
car=struct() % specify all fields at once cars=[car;car] cars(2).mpg=40 cars.mpg returns all mpg Cell1={1 2 3;'test1',[1;2],false}
cell of arrays: c{1}=[31 7];c{2}=[3 78]; c{:} accessing one array of the cell: c{1} copy single input to all requested outputs with deal() [Y1, Y2, Y3, ...] = deal(X) same as Y1=X, Y2=X, Y3=X, ... [Y1, Y2, Y3, ...] = deal(X1, X2, X3, ...) same as Y1=X1; Y2=X2; Y3=X3; ...
% INFORMATION ON A FUNCTION HANDLE FOR A GIVEN FUNCTION f=functions(@poly) % it has 3 fields; function, type, file f.type
% FUNCTION HANDLE FROM FUNCTION NAME STRING MATLAB SIMULINK Assignments 7.7.2 ANNEX Basic Exercises 2______________ .
John Bofarull Guix, attached; -- 6 / 13 % no access to nested functions, use @ for nested functions access
fh=str2func('sin') % fh=@sin function fh=makeHandle(funcname) fh=str2func(funcname) % makeHandle('sin') % ans=@sin
% CELL ARRAY OF FUNCTION HANDLES fh_array=cellfun(@str2func, {'sin' 'cos' 'tan'}, ... 'UniformOutput', false); fh_array{2} (5) % ans = cos(5)=.2837
fhandle=@sin; % FUNCTION NAME STRING TO FUNCTION HANDLE func2str(fhandle) % ans = sin
function catcherr(func, data) try ans=func(data); disp('Answer is:'); ans catch disp(sprintf('Error erxecuting function ''%s''\n', ... funct2str(func))) end
%call that resturns no evaluation error; catcherr(@round, 5.432) % ans= Answer is 5
xstuct.value=5.432;catcherr(@round,xstruct) % call that catches evaluation error Error executing function "round"
isa(rand(3,4),'double') % ISA polynom_obj=polynom([1 0 -2 -5]); isa(polynom_obj,'polynom') % isa type parameter: logical, char,numeric, integer, % int8, uint8, int16, uint16, int32, uint32, int64, uint64, % float, single, double, cell, struct, function_handle, % 'class_handle'
hold on; % marker on peak index=find(power==max(power)); mainPeriodStr=num2str(period(index)); plot(period(index),power(index),'r.', 'MarkerSize',25); text(period(index)+2,power(index),['Period = ',mainPeriodStr]); hold off;
% differentiation syms x; f=sin(5*x); diff(f); ans = 5*cos(5*x) g=exp(x)*cos(x); diff(g); ans = exp(x)*cos(x)-exp(x)*sin(x) diff(g,2); diff(diff(g)) c=sym('5'); diff(c); diff(5)
syms s t f=sin(s*t) diff(f,t) diff(f,s) findsym(f,1) diff(f,t,2)
syms a b x n t theta f=x^n; diff(f) f=sin(a*t+b); diff(f) f=exp(i*theta); diff(f)
% Bessel function 1st kind syms nu z b=besselj(nu,z) db=diff(b)
syms a x A=[cos(a*x),sin(a*x);-sin(a*x),cos(a*x)] diff(A)
syms r l f % Jacobian x=r*cos(l)*cos(f); y=r*cos(l)*sin(f); z=sin(l); J=jacobian([x;y;z],[r l f]) detJ=simple(det(J))
syms h n x % Limits limit((cos(x+h)-cos(x))/h,h,0) limit((1+x/n)^n,n,inf) limit(x/abs(x),x,0,'left') limit(x/abs(x),x,0,'right') limit(x/abs(x),x,0) % NaN
int(x^n); int(x^n,x) % Integration int(sin(2*x),0,pi/2); int(sin(2*x),x,0,pi/2) g=cos(a*t+b); int(g,t) int(beselj(1,z),z) syms a b theta x y n u z
syms z a=int(besselj(1,z)^2,0,1); a=double(a); 0.717
% paretotail example to construct piecewise distributions % available methods: cdf, disp, display, icdf, nsegments, pdf, random, segment t = trnd(3,100,1); obj = paretotails(t,0.1,0.9); [p,q] = boundary(obj); x = linspace(-5,5); plot(x,cdf(obj,x),'b-','LineWidth',2) hold on plot(x,tcdf(x,3),'r:','LineWidth',2) plot(q,p,'bo','LineWidth',2,'MarkerSize',5) legend('Pareto Tails Object','t Distribution',... 'Location','NW')
% Integration with R parameters syms x; a=sym(1/2); f=exp(-a*x^2); ezplot(f) syms a positive; syms x; f=exp(-a*x^2); int(f,x,-inf,inf)
% integration complex domain syms a x clear; f=1/(a^2+x^2); F=int(f,x,-inf,inf) syms a x clear; f = 1/(a^2 + x^2); F = int(f, x, -inf, inf); F = (pi*signIm(i/a))/a g=subs(F,1+i); double(g)
% Symbolic summation syms x k s1=symsum (1/k^2,1,inf) s2=symsum(x^k,k,0,inf); s1=pi^2/6; s2=piecewise([1<=x,Inf],[abs(x)<1,-1/(x-1)])
% Taylor series syms x; f=1/(5+4*cos(x)); T=taylor(f,8); pretty(T) syms x; g=exp(x*sin(x));t=taylor(g,12,2); size(char(t)) t=simplify(t); size(char(t)); t=simple(t); size(char(t)); xd=1:0.05:3; yd=subs(g,x,xd); ezplot(t,[1,3]); hold on; plot(xd, yd, 'r-.'); title('Taylor approximation vs actual function'); legend('Taylor','Function')
% Function definitions syms x; num = 3*x^2 + 6*x -1; denom = x^2 + x - 3; f = num/denom; ezplot(f)
% Asymptotes limit(f,inf); roots=solve(denom); ezplot(f); hold on;plot([-2*pi 2*pi], [3 3],'g') plot(double(roots(1))*[1 1], [-5 10],'r'); plot(double(roots(2))*[1 1], [-5 10],'r') title('Horizontal and Vertical Asymptotes'); hold off
%Max Mins f1=diff(f); f1=simplify(f1); pretty(f1); crit_points=solve(f1); ezplot(f); hold on; plot(double(crit_pts), double(subs(f,crit_pts)),'ro') title('Maximum and Minimum of f'); text(-5.5,3.2,'Local minimum') text(-2.5,2,'Local maximum'); hold off
since x(n)=sum(-inf,inf,x(k)*delta(n-k)) and from the above p&s calculation, Problem 2.1.2 is interleaving zeros into an original sequence k=-5,5, exp(-abs(k))
What command will return the corner elements of a 10-by-10 matrix A?
**A. A([1,end], [1,end]) B. A([1,1], [end,end]) returns 2x2 with same A(1,:) central element C. A({[1,1], [1,end], [end,1], [end,end]}) what strings format has to do with selecting elements from matrix? D. A(1:end, 1:end) =A
What command will return the fraction of positive numbers in a 10-by-10 matrix A?
A. A(A > 0)/A error. Had it been ../det(A), since det(A)=0 yet MATLAB answers B. numel(A > 0)/numel(A) C. sum(A > 0)/prod(size(A)) **D. nnz(A > 0)/numel(A) %% 0 is neither positive nor negative so it is not taken into account
What command will delete (completely remove) the last cell of a cell-array C?
A. C{end} = []; B. C[end] = []; ** C. C(end) = []; D. C{end} = {[]};
What command will create a plot of acceleration vs. time (i.e., a vector time on the x-axis and a vector acceleration on the y-axis)?
** A. plot(time, acceleration) B. plot(acceleration, time) C. plot([time, acceleration]) D. plot([acceleration, time])
What command will give the standard deviation for each column in a 10-by-5 matrix Z?
A. std(Z(:)) B. std(std(Z)) ** C. std(Z(1:5, :)) D. std(Z)