Download presentation
Published byMildred Fisher Modified over 9 years ago
1
Rutgers University School of Engineering Spring :440:127 - Introduction to Computers for Engineers Sophocles J. Orfanidis ECE Department week 13
2
Weekly Topics Week Basics – variables, arrays, matrices, plotting (ch. 2 & 3) Week Basics – operators, functions, strings, cells (ch. 2,3,11) Week Matrices (ch. 4) Week Plotting – 2D and 3D plots (ch. 5) Week User-defined functions (ch. 6) Week Input-output formatting – fprintf, fscanf (ch. 7) – Exam 1 Week Relational & logical operators, if, switch statements (ch. 8) Week For-loops, while-loops (ch. 9) Week Review for weeks 5-8 Week 10 - Matrix algebra – solving linear equations (ch. 10) – Exam 2 Week 11 - Numerical methods I (ch. 13) Week 12 - Numerical methods II (ch. 13) Week 13 - Strings, structures, cell arrays, symbolic math (ch. 11,12) Week 14 – Exam 3 References: H. Moore, MATLAB for Engineers, 4/e, Prentice Hall, 2014 G. Recktenwald, Numerical Methods with MATLAB, Prentice Hall, 2000 A. Gilat, MATLAB, An Introduction with Applications, 4/e, Wiley, 2011
3
Strings, Structures, Cells, Symbolic Math
characters and strings concatenating strings using num2str comparing strings with strcmp structure arrays converting structures to cells cell arrays cell vs. content indexing varargin, varargout multi-dimensional arrays symbolic math
4
MATLAB Data Classes Character Logical Numeric Symbolic Cell Structure Integer Floating Point signed unsigned single precision double precision More Classes Cell and Structure arrays can store different types of data in the same array Java classes user-defined classes function handles
5
Characters and Strings
Strings are arrays of characters. Characters are represented internally by standardized numbers, referred to as ASCII (American Standard Code for Information Interchange) codes. see Wikipedia link: ASCII table >> c = 'A' c = A >> x = double(c) x = 65 % ASCII code for 'A' >> char(x) ans = >> class(c) char char() creates a character string >> doc char >> doc class
6
s is a row vector of 8 characters
>> s = 'ABC DEFG' s = ABC DEFG >> x = double(s) x = >> char(x) ans = >> size(s) >> class(s) char ASCII codes convert ASCII codes to characters s is a row vector of 8 characters >> s(2), s(3:5) ans = B C D
7
Concatenating Strings
s = ['Albert', 'Einstein'] s = AlbertEinstein >> s = ['Albert', ' Einstein'] Albert Einstein >> s = ['Albert ', 'Einstein'] >> size(s) ans = preserve leading and trailing spaces >> doc strcat >> doc strvcat >> doc num2str >> doc strcmp >> doc findstr
8
Concatenating Strings
s = strcat('Albert ', 'Einstein') s = AlbertEinstein >> s = strcat('Albert', ' Einstein') Albert Einstein >> fmt = strcat(repmat('%8.3f ',1,6),'\n') fmt = %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n strcat strips trailing spaces but not leading spaces use repmat to make up long format strings for use with fprintf
9
Concatenating Vertically
s = ['Apple'; 'IBM'; 'Microsoft']; ??? Error using ==> vertcat CAT arguments dimensions are not consistent. s = ['Apple '; 'IBM '; 'Microsoft'] s = Apple IBM Microsoft >> size(s) ans = padded with spaces to the length of the longest string
10
Concatenating Vertically
s = strvcat('Apple', 'IBM', 'Microsoft'); s = char('Apple', 'IBM', 'Microsoft'); s = Apple IBM Microsoft >> size(s) ans = strvcat,char both pad spaces as necessary Recommendation: use char to concatenate vertically, and [] to concatenate horizontally
11
num2str a = [143.87, -0.0000325, -7545]'; >> s = num2str(a) s =
-3.25e-005 -7545 >> s = num2str(a,4) 143.9 >> s = num2str(a, '%12.6f') num2str s = num2str(A) s = num2str(A, precision) s = num2str(A, format) max number of digits format spec
12
num2str a = [143.87, , -7545]'; >> s = num2str(a, '%10.5E') s = E+002 E-005 E+003 b = char('A', 'BB', 'CCC'); >> disp([b, repmat(' ',3,1), s]) A E+002 BB E-005 CCC E+003
13
num2str Labeling and saving multiple plots with saved as
t = linspace(0,5,101); w = [2,5,8,10]; Y = sin(w'*t); % 4x101 matrix s = char('b-', 'r-', 'm-', 'g-'); for i=1:4, figure; plot(t,Y(i,:), s(i,:)); title(['sin(', num2str(w(i)), 't)']); print('-depsc', ['file',num2str(i),'.eps']); end Labeling and saving multiple plots with num2str saved as file1.eps, file2.eps file3.eps, file4.eps
14
Comparing Strings Strings are arrays of characters, so the condition s1==s2 requires both s1 and s2 to have the same length >> s1 = 'short'; s2 = 'shore'; >> s1==s1 ans = >> s1==s2 >> s1 = 'short'; s2 = 'long'; ??? Error using ==> eq Matrix dimensions must agree.
15
strings of unequal length, and get a binary decision
Comparing Strings Use strcmp to compare strings of unequal length, and get a binary decision >> s1 = 'short'; s2 = 'shore'; >> strcmp(s1,s1) ans = 1 >> strcmp(s1,s2) >> s1 = 'short'; s2 = 'long'; >> doc strcmp >> doc strcmpi case-insensitive
16
Useful String Functions
sprintf - write formatted string sscanf read formatted string deblank - remove trailing blanks strcmp - compare strings strcmpi - compare strings strmatch - find possible matches upper convert to upper case lower convert to lower case blanks - string of blanks strjust - left/right/center justify string strtrim - remove leading/trailing spaces strrep - replace strings findstr - find one string within another
17
Structures have named ‘fields’ that can
store all kinds of data: vectors, matrices, strings, cell arrays, other structures name.field student.name = 'Apple, A.'; % string student.id = 12345; % number student.exams = [85, 87, 90]; % vector student.grades = {'B+', 'B+', 'A'}; % cell >> student student = name: 'Apple, A.' id: 12345 exams: [ ] grades: {'B+' 'B+' 'A'} >> class(student) ans = struct structures can also be created with struct()
18
Structure Arrays add two more students with partially defined fields,
rest of fields are still empty structure array index student(2).name = 'Twitter, T.'; student(3).id = ; >> student student = 1x3 struct array with fields: name id exams grades
19
Structure Arrays >> student(1) ans = name: 'Apple, A.' id: 12345
exams: [ ] grades: {'B+' 'B+' 'A'} >> student(2) ans = name: 'Twitter, T.' id: [] exams: [] grades: [] >> student(3) ans = name: [] id: exams: [] grades: []
20
Structure Arrays the missing field values can be defined later and don’t have to be of the same type or length as those of the other entries >> student(3).exams = [70 80]; >> student(3) ans = name: [] id: exams: [70 80] grades: []
21
Accessing Structure Elements
>> student(1) ans = name: 'Apple, A.' id: 12345 exams: [ ] grades: {'B+' 'B+' 'A'} >> student(1).name(5) % ans = % e >> student(1).exams(2) % ans = % 87 >> student(1).grades(3) % ans = % 'A' >> student(1).grades{3} % ans = % A cell vs. content indexing
22
s.a = [1 2; 3 4]; s.b = {'a', 'bb'; 'ccc', 'dddd'}; >> s s = a: [2x2 double] b: {2x2 cell} >> s.a ans = >> s.a(2,2) 4 >> s.b ans = 'a' 'bb' 'ccc' 'dddd' >> s.b(2,1), s.b{2,1} 'ccc' ccc cell vs. content indexing
23
Nested Structures student.name = 'Apple, A.'; student.id = 12345;
student.work.exams = [85, 87, 90]; student.work.grades = {'B+', 'B+', 'A'}; >> student student = name: 'Apple, A.' id: 12345 work: [1x1 struct] >> student.work % sub-structure ans = exams: [ ] grades: {'B+' 'B+' 'A'}
24
Stucture Functions struct - create structure
fieldnames - get structure field names isstruct test if a structure isfield test if a field rmfield remove a structure field struct2cell - convert structure to cell array >> C = struct2cell(student) C = 'Apple, A.' [ ] [1x1 struct] >> C{3} ans = exams: [ ] grades: {'B+' 'B+' 'A'} content indexing
25
Like structures, cell arrays are containers
of all kinds of data: vectors, matrices, strings, structures, other cell arrays, functions. A cell is created by putting different types of objects in curly brackets { }, e.g., c = {A, B, C, D}; % 1x4 cell c = {A; B; C; D}; % 4x1 cell c = {A, B; C, D}; % 2x2 cell where A,B,C,D are arbitrary objects c{i,j} accesses the data in i,j cell c(i,j) is the cell object in the i,j position Cell Arrays cell vs. content indexing
26
A = {'Apple'; 'IBM'; 'Microsoft'}; % cells
B = [1 2; 3 4]; % matrix C x.^2 + 1; % function D = [ ]; % row c = {A,B;C,D} % define 2x2 cell array c = {3x1 cell} [2x2 double] @(x)x.^2+1 [1x5 double] >> cellplot(c);
27
A = {'Apple'; 'IBM'; 'Microsoft'}
S = char('Apple', 'IBM', 'Microsoft') S = Apple IBM Microsoft >> size(A), class(A) ans = cell comparing cell arrays of strings vs. strings >> size(S), class(S) ans = char
28
>> S Apple IBM Microsoft >> S' AIM pBi pMc l r e o s o f t >> A(2), class(A(2)) ans = 'IBM' cell cell vs. content indexing >> A{2}, class(A{2}) ans = IBM char >> A' ans = 'Apple' 'IBM' 'Microsoft'
29
A = {'Apple'; 'IBM'; 'Microsoft'}; % cells
B = [1 2; 3 4]; % matrix C x.^2 + 1; % function D = [ ]; % row c = {A,B;C,D} % define 2x2 cell array c = {3x1 cell} [2x2 double] @(x)x.^2+1 [1x5 double] >> cellplot(c);
30
content indexing with { }
>> celldisp(c) c{1,1}{1} = Apple c{1,1}{2} = IBM c{1,1}{3} = Microsoft c{2,1} = @(x)x.^2+1 c{1,2} = c{2,2} = content indexing with { } >> c{1,1} ans = 'Apple' 'IBM' 'Microsoft' >> c{2,1} @(x)x.^2+1
31
content indexing with { }
ans = Microsoft >> c{1,1}{3}(6) s >> x = [1 2 3]; >> c{2,1}(x) >> fplot(c{2,1},[0,3]); content indexing with { } >> c{1,2}(2,:) ans = >> c{1,2}(1,2) 2 >> c{2,2}(3) 30
32
cell indexing ( ) content indexing { } cell cell contents
ans = [1x5 double] >> class(c(2,2)) cell >> c{2,2} >> class(c{2,2}) double cell cell contents
33
cell indexing ( ) content indexing { } cell cell contents
ans = 'IBM' >> class(c{1,1}(2)) cell >> c{1,1}{2} IBM >> class(c{1,1}{2}) char cell cell contents
34
>> d = c; >> % d(1,3) = {[4 5 6]'}; % define as cell >> d{1,3} = [4,5,6]' % define content d = {3x1 cell} [2x2 double] [3x1 double] @(x)x.^2+1 [1x5 double] [] >> d(2,3) ans = {[]} >> d{2,3} [] >> cellplot(d);
35
try also >> e = reshape(d,3,2) >> cellplot(e)
>> f = repmat(c,1,2) >> cellplot(f) try also >> f = d';
36
changing cell array contents could have used: why not ?
>> c{1,1}{2} = 'Google'; >> c{1,2} = 10*c{1,2}; >> c{2,2}(3) = 300; >> celldisp(c) c{1,1}{1} = Apple c{1,1}{2} = Google c{1,1}{3} = Microsoft c{2,1} = @(x)x.^2+1 c{1,2} = c{2,2} = changing cell array contents could have used: c{1,1}(2) = {'Google'}; why not ? c(1,2) = 10*c(1,2); c{2,2}{3} = 300;
37
num2cell cell2mat >> A = [1 2; 3 4]; >> C = num2cell(A)
cell2mat converts numerical cell arrays to numbers num2cell converts numerical array to cell array >> A = [1 2; 3 4]; >> C = num2cell(A) C = [1] [2] [3] [4] >> B = cell2mat(C) B =
38
num2cell cell2mat >> A = [1,2; 3,4]; % 2x2 matrix
>> S = {'a', 'bb'; 'ccc', 'dddd'}; % 2x2 cell S = 'a' 'bb' 'ccc' 'dddd' >> [A,S] % can’t mix numbers and cells ??? Error using ==> horzcat CAT arguments dimensions are not consistent. >> [num2cell(A),S] % construct 2x4 cell ans = [1] [2] 'a' 'bb' [3] [4] 'ccc' 'dddd'
39
using num2cell with fprintf
S = {'January', 'April', 'July', 'October'}; T = [30, 60, 80, 70]; C = [S;T] % can’t mix numbers and cells ??? Error using ==> vertcat CAT arguments dimensions are not consistent. C = [S; num2cell(T)] % make all into cells C = 'January' 'April' 'July' 'October' [ ] [ 60] [ 80] [ ] fprintf(' %-7s %5.2f\n', C{:}); January April July October >> class(C) ans = cell >> C(:) 'January' [30] 'April' [60] 'July' [80] 'October' [70] read content column-wise print it row-wise
40
num2cell fprintf column vectors transposed content indexing
M = {'January'; 'April'; 'July'; 'October'}; T1 = [30; 60; 80; 70]; T2 = [-10; 40; 60; 50]; C = [M, num2cell([T1,T2])]' % C = % 'January' 'April' 'July' 'October' % [ ] [ 60] [ 80] [ ] % [ ] [ 40] [ 60] [ ] fprintf(' T T2\n') fprintf(' \n') fprintf('%-7s %6.2f %6.2f\n',C{:}) % fprintf('%-7s %6.2f %6.2f\n',C{:,:}) T T2 January April July October num2cell fprintf column vectors transposed >> C(:) ans = 'January' [ 30] [-10] 'April' [ 60] [ 40] 'July' [ 80] 'October' [ 70] [ 50] content indexing
41
varargin varargout varargin,varargout are cell arrays that allow the passing a variable number of function inputs & outputs % [x,y,vx,vy] = trajectory(t,v0,th0,h0,g) function [varargout] = trajectory(t,v0,varargin) Nin = nargin-2; % number of varargin inputs if Nin==0, th0=90; h0=0; g=9.81; end if Nin==1, th0=varargin{1}; h0=0; g=9.81; end if Nin==2, th0=varargin{1}; ... h0=varargin{2}; g=9.81; end if Nin==3, th0=varargin{1}; ... h0=varargin{2}; g=varargin{3}; end continues
42
th0 = th0 * pi/180; % convert to radians
x = v0 * cos(th0) * t; y = h0 + v0 * sin(th0) * t - 1/2 * g * t.^2; vx = v0 * cos(th0); vy = v0 * sin(th0) - g * t; if nargout==1; varargout{1} = x; end if nargout==2; varargout{1} = x; ... varargout{2} = y; end if nargout==3; varargout{1} = x; varargout{2} = y; ... varargout{3} = vx; end if nargout==4; varargout{1} = x; ... varargout{3} = vx; ... varargout{4} = vy; end
43
Multidimensional Arrays
A three-dimensional array is a collection of two-dimensional matrices of the same size, and are characterized by triple indexing, e.g., A(i,j,p) is the (i,j) matrix element of the p-th matrix. Higher-dimensional arrays can also be defined, e.g., a 4D array is a collection of 3D arrays of the same size. applications in video processing
44
pages can operate along the i,j,p dimensions >> a = [1 2; 3 4];
>> A(:,:,1) = a; >> A(:,:,2) = 10*a; >> A(:,:,3) = 100*a; >> A A(:,:,1) = A(:,:,2) = A(:,:,3) = pages sum, min, max can operate along the i,j,p dimensions
45
>> sum(A,1) ans(:,:,1) = ans(:,:,2) = ans(:,:,3) = >> sum(A,2) 3 7 30 70 300 700 A(:,:,1) = A(:,:,2) = A(:,:,3) = >> sum(A,3) ans =
46
>> min(A,[],1) ans(:,:,1) = ans(:,:,2) = ans(:,:,3) = >> min(A,[],2) 1 3 10 30 100 300 A(:,:,1) = A(:,:,2) = A(:,:,3) = >> min(A,[],3) ans =
47
column-order across pages >> A>20 & A<300 ans(:,:,1) = 0 0
ans(:,:,2) = ans(:,:,3) = >> k = find(A>20 & A<300) k = 6 8 9 11 A(:,:,1) = A(:,:,2) = A(:,:,3) = column-order across pages
48
Symbolic Math Toolbox Creating and manipulating symbolic variables
Factoring and simplifying algebraic expressions Solving symbolic equations Linear algebra operations Performing summation of infinite series Taylor series expansions, limits Differentiation and integration Solving differential equations Fourier, Laplace, Z-transforms and inverses Variable precision arithmetic
49
MATLAB Data Classes Character Logical Numeric Symbolic Cell Structure Integer Floating Point signed unsigned single precision double precision More Classes Java classes user-defined classes function handles Symbolic data types are created with sym,syms
50
>> help symbolic >> doc symbolic >> doc sym
>> syms x y z >> syms x y z real >> syms x y z positive >> x = sym('x'); >> help symbolic >> doc symbolic >> doc sym >> doc syms >> sym(sqrt(2)) ans = 2^(1/2) >> sqrt(sym(2)) >> double(ans) 1.4142 >> f = x^6-1 f = x^6 - 1 >> g = x^3 +1 g = x^3 + 1
51
>> a = [0, pi/6, pi/4, pi/2, pi]; >> cos(a) ans =
>> c = cos(sym(a)) c = [ 1, 3^(1/2)/2, 2^(1/2)/2, 0, -1] >> symdisp(c) >> pretty(c) | /2 1/ | | | | 1, ----, ----, 0, -1 | | | display symbolic expression using LaTeX – on sakai
52
>> f = x^6-1; >> g = x^3 +1; >> r = f/g % x^6-1 = (x^3-1)*(x^3+1) r = (x^6 - 1)/(x^3 + 1) >> pretty(r) % pretty print 6 x - 1 3 x + 1 >> symdisp(r)
53
Functions for factoring and simplification of algebraic expressions:
simplify - Simplify expand Expand factor Factor collect Collect simple Search for shortest form numden Numerator and denominator subs Symbolic substitution
54
factor >> simplify(r) ans = x^3 - 1
>> factor(simplify(r)) % x^3 - 1 (x - 1)*(x^2 + x + 1) >> factor(g) % x^3 + 1 (x + 1)*(x^2 - x + 1) >> factor(f) % x^6 - 1 (x - 1)*(x + 1)*(x^2 + x + 1)*(x^2 - x + 1)
55
expand >> syms x a b; >> expand((x+1)*(x+2)) ans =
>> expand(exp(a+b)) exp(a)*exp(b) >> expand(cos(a+b)) cos(a)*cos(b) - sin(a)*sin(b) >> expand(cosh(a+b)) sinh(a)*sinh(b) + cosh(a)*cosh(b)
56
expand >> A = [sin(2*x), sin(3*x) cos(2*x), cos(3*x)] A =
>> B = expand(A) B = [2*cos(x)*sin(x), 3*cos(x)^2*sin(x)-sin(x)^3] [cos(x)^2-sin(x)^2, cos(x)^3-3*cos(x)*sin(x)^2] >> expand((a+b)*(a^2+2*a*b+b^2)) ans = a^3 + 3*a^2*b + 3*a*b^2 + b^3 expand
57
collect >> collect((x+1)*(x+2)) ans = x^2 + 3*x + 2
>> collect((a+b)*(a^2 + 2*a*b + b^2), a) a^3 + (3*b)*a^2 + (3*b^2)*a + b^3 >> collect((a+b)*(a^2 + 2*a*b + b^2), b) b^3 + (3*a)*b^2 + (3*a^2)*b + a^3 >> factor(a^3 + 3*a^2*b + 3*a*b^2 + b^3) (a + b)^3 collect
58
simplify >> simplify(a^3 + 3*a^2*b + 3*a*b^2 + b^3) ans =
>> simplify(cos(b)*sin(a) - cos(a)*sin(b)) sin(a - b) B = [2*cos(x)*sin(x), 3*cos(x)^2*sin(x)-sin(x)^3] [cos(x)^2-sin(x)^2, cos(x)^3-3*cos(x)*sin(x)^2] >> simplify(B) [ sin(2*x), sin(3*x)] [ cos(2*x), cos(3*x)]
59
numden >> [num,den] = numden(1 + 2*x + 3/(x^2+5)) num =
2*x^3 + x^2 + 10*x + 8 den = x^2 + 5 >> symdisp(1 + 2*x + 3/(x^2+5)) >> symdisp(num/den)
60
subs >> syms x a b x,a,b class sym >> y = a*x+b y =
b + a*x >> y1 = subs(y,a,3) y1 = b + 3*x >> y2 = subs(y,b,5) y2 = a*x + 5 >> y3 = subs(y,{a,b},{3,5}) y3 = 3*x + 5 >> a=2; b=4; y4 = subs(y) y4 = 2*x + 4 x,a,b class sym subs a,b taken from workspace a,b class double
61
Functions for solving algebraic and differential equations:
solve solve algebraic equations. dsolve solve differential equations. finverse - Functional inverse. compose Functional composition.
62
Solving symbolic equations
>> syms x a b c; >> f = a*x^2 + b*x + c; >> xsol = solve(f) xsol = -(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a) >> xsol(1), xsol(2) ans = symdisp(xsol(1));
63
>> g = a*(x-xsol(1))*(x-xsol(2))
a*(x + (b + (b^2 - 4*a*c)^(1/2))/(2*a))*(x + (b - (b^2 - 4*a*c)^(1/2))/(2*a)) >> simplify(g) ans = a*x^2 + b*x + c >> a*xsol(1)^2 + b*xsol(1) + c c + (b + (b^2 - 4*a*c)^(1/2))^2/(4*a) - (b*(b + (b^2 - 4*a*c)^(1/2)))/(2*a) >> simplify(a*xsol(1)^2 + b*xsol(1) + c)
64
solving equations some variations
>> xsol = solve('a*x^2 + b*x + c'); >> xsol = solve('a*x^2 + b*x + c=0'); >> xsol = solve('a*x^2 + b*x + c','x'); >> xsol = solve(a*x^2 + b*x + c, x); >> syms z; >> xsol = solve(a*z^2 + b*z + c) xsol = -(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a) >> bsol = solve(a*x^2 + b*x + c, b) bsol = -(a*x^2 + c)/x
65
solving equations >> syms a b p u w y z
>> solve(a+b+p), solve(a+b+w) ans = - a - b >> solve(u+w+z) - u - z >> solve(w+y+z) - w - z solving equations how does it know which variable to solve for? alphabetically closest to ‘x’ >> syms x a b c; >> f = a*x^2 + b*x + c; >> xsol = solve(f) xsol = -(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a)
66
solving equations class double golden ratio
>> f1 = subs(f,{a,b,c},{1,1,-1}) f1 = x^2 + x – 1 >> x1 = solve(f1) x1 = 5^(1/2)/2 - 1/2 - 5^(1/2)/2 – 1/2 >> subs(xsol,{a,b,c},{1,1,-1}) ans = 0.6180 >> phi = simplify(1./x1) phi = 5^(1/2)/2 + 1/2 1/2 - 5^(1/2)/2 solving equations x1 class sym class double golden ratio
67
Fibonacci numbers, F(n) = F(n-1)+F(n-2) = [0, 1, 1, 2, 3, 5, 8, 13, …]
>> syms n >> F = (phi(1)^n – phi(2)^n)/(phi(1)-phi(2)); >> simplify(F - subs(F,n,n-1) - subs(F,n,n-2)) ans = >> limit(F/subs(F,n,n-1), n, inf) 2/(5^(1/2) - 1) >> simplify(limit(F/subs(F,n,n-1), n,inf)) 5^(1/2)/2 + 1/2 golden ratio
68
solving equations >> eq1 = 'x^2 + x -1=0'; >> solve(eq1)
ans = 5^(1/2)/2 - 1/2 - 5^(1/2)/2 - 1/2 >> eq2 = '1/x = x/(1-x)'; >> solve(eq2) >> solve('1/x = x/(1-x)');
69
solving equations >> eq1 = 'x^2 + y - 1=0';
>> [x,y] = solve(eq1,eq2) x = 5^(1/2)/2 + 1/2 1/2 - 5^(1/2)/2 y = - 5^(1/2)/2 - 1/2 5^(1/2)/2 – 1/2 >> eval(x) % or, double(x) ans = 1.6180
70
solving equations returned as a structure of syms
>> [x,y] = solve('x+y=1', 'x^2+y^2=1'); >> [x,y] ans = [ 1, 0] [ 0, 1] >> S = solve('x+y=1', 'x^2+y^2=1') S = x: [2x1 sym] y: [2x1 sym] >> [S.x, S.y] returned as a structure of syms
71
linear equations >> A = [ 5 1 3 0 1 4 1 1 -1 2 6 -2 1 -1 1 4];
]; >> A = sym(A) A = [ 5, 1, 3, 0] [ 1, 4, 1, 1] [ -1, 2, 6, -2] [ 1, -1, 1, 4] >> inv(A) ans = [ 53/274, -2/137, -12/137, -11/274] [ -21/548, 34/137, -3/274, -37/548] [ 13/548, -8/137, 41/274, 49/548] [ -35/548, 11/137, -5/274, 121/548] from homework-9
72
linear equations >> b = [12; -3; 11; 10];
>> x = inv(A)*b % or, A\b x = 1 -2 3 >> class(x) ans = sym
73
polynomials >> f = 5*x^4 - 2*x^3 + x^2 + 4*x + 3 f =
>> p = sym2poly(f) p = >> poly2sym(p) ans = >> poly2sym(p,'t') 5*t^4 - 2*t^3 + t^2 + 4*t + 3 polynomials poly2sym sym2poly coeffs quorem roots poly
74
polynomials >> [q,mono] = coeffs(f) q = [ 5, -2, 1, 4, 3] mono =
[ x^4, x^3, x^2, x, 1] >> p = sym2poly(f) p = >> z = roots(p) z = i i i i polynomials poly2sym sym2poly coeffs quorem roots poly
75
polynomials >> p = sym2poly(f) p = 5 -2 1 4 3
>> z = roots(p) z = i i i i >> P = poly(z) P = >> 5*P ans = polynomials poly2sym sym2poly coeffs quorem roots poly
76
>> f = 5*x^4 - 2*x^3 + x^2 + 4*x + 3;
>> x1 = linspace(-1,1,201); >> f1 = subs(f,x1); % or, f1 = subs(f,x,x1); >> plot(x1,f1,'b'); >> xlabel('x'); >> ylabel('f(x)');
77
symsum >> syms n >> symsum(1/n^2, n, 1, inf) ans = pi^2/6
78
symsum >> syms x n N >> symsum(x^n, n, 0, N-1)
piecewise([x = 1, N], [x <> 1,... (x^N - 1)/(x - 1)]) >> symsum(x^n, n, 0, inf) piecewise([1 <= x, Inf],... [abs(x) < 1, -1/(x - 1)]) >> symsum(x^n/sym('n!'), n, 0, inf) ans = exp(x) >> symsum(n^2, n, 1, N) (N*(2*N + 1)*(N + 1))/6 finite & infinite geometric series
79
Taylor series >> syms x >> taylor(exp(x)) ans =
x^5/120 + x^4/24 + x^3/6 + x^2/2 + x + 1 >> taylor(exp(x),4) x^3/6 + x^2/2 + x + 1 >> taylor(sin(x),4) x - x^3/6 >> taylor(sin(x)/x) x^4/120 - x^2/6 + 1 Taylor series
80
limits >> syms x >> limit(exp(-x), x, inf) ans =
>> limit(sin(x)/x, x, 0) 1 >> limit(cos(pi*cos(x)/2)/x, x, 0) >> taylor(cos(pi*cos(x)/2)/x,2) (pi*x)/4 limits
81
simple calculus differentiation integration >> syms x
>> diff(x^2) ans = 2*x >> diff(x^3) 3*x^2 >> diff(cos(x)) ans -sin(x) >> syms x >> int(x^2) ans = x^3/3 >> int(cos(x)) sin(x) >> int(cos(x)^2, 0, pi) pi/2 simple calculus differentiation integration
82
dsolve acceleration with air drag terminal velocity and time constant
solve with initial velocity v(0) = v0 exact solution
83
dsolve D = derivative >> syms v t va ta v0
>> diffeq = 'Dv=va/ta*(1-v^2/va^2)'; >> v = dsolve(diffeq, 'v(0)=v0') v = -va*tan(-va*(- t/(ta*va) + (atan((v0*i)/va)*i)/va)*i)*i >> v = simplify(v) va^2/v0 + (va*(v0^2 - va^2))/(v0*(va + v0*tanh(t/ta))) >> [num,den] = numden(v);
84
dsolve >> v = num/den v =
(tanh(t/ta)*va^2 + v0*va)/(va + v0*tanh(t/ta)) >> symdisp(v); >> u = va*tanh(t/ta + atanh(v0/va)); >> simplify(v-u) ans =
85
dsolve >> subs(v,t,0) ans = V0 >> t1 = linspace(0,30,301);
>> v1 = subs(v, {va,ta,v0,t}, {30,10,0,t1}); >> plot(t1,v1,'b'); >> xlabel('t'); >> ylabel('v(t)');
86
dsolve v0 = 0; va = 30; ta = 10; tspan = [0,30];
vdot va/ta * (1 - v.^2/va^2); [t2,v2] = ode45(vdot, tspan, v0); plot(t2,v2,'r-') xlabel('t'); ylabel('v(t)'); compare exact and numerical solutions using ode45
87
compare exact and numerical solutions using forward Euler method, which replaces derivatives by forward differences dsolve
88
dsolve Tspan = 30; N = 60; T = Tspan/N;
tn = 0:T:Tspan; % tn = 0:0.5:30 vn(1) = v0; for n=1:N, vn(n+1) = vn(n) + T*va/ta*(1-vn(n)^2/va^2); end plot(t1,v1,'b'); hold on; plot(tn,vn,'r--') compare exact and numerical solutions using forward Euler
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.