Rutgers University School of Engineering Spring 2015 14:440:127 - Introduction to Computers for...

Preview:

DESCRIPTION

Weekly Topics Week 1 - Basics – variables, arrays, matrices, plotting (ch. 2 & 3) Week 2 - Basics – operators, functions, strings, cells (ch. 2,3,11) Week 3 - Matrices (ch. 4) Week 4 - Plotting – 2D and 3D plots (ch. 5) Week 5 - User-defined functions (ch. 6) Week 6 - Input-output formatting – fprintf, fscanf (ch. 7) – Exam 1 Week 7 - Relational & logical operators, if, switch statements (ch. 8) Week 8 - For-loops, while-loops (ch. 9) Week 9 - 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

Citation preview

Rutgers UniversitySchool of Engineering

Spring 2015

14:440:127 - Introduction to Computers for Engineers

Sophocles J. OrfanidisECE Department

orfanidi@ece.rutgers.edu

week 13

Week 1 - Basics – variables, arrays, matrices, plotting (ch. 2 & 3)Week 2 - Basics – operators, functions, strings, cells (ch. 2,3,11)Week 3 - Matrices (ch. 4)Week 4 - Plotting – 2D and 3D plots (ch. 5)Week 5 - User-defined functions (ch. 6)Week 6 - Input-output formatting – fprintf, fscanf (ch. 7) – Exam 1Week 7 - Relational & logical operators, if, switch statements (ch. 8)Week 8 - For-loops, while-loops (ch. 9) Week 9 - Review for weeks 5-8Week 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

Weekly Topics

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

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

MATLAB Data Classes

Character

Floating Point

single precision

double precision

Logical Numeric Symbolic Cell Structure

More Classes Cell and Structure arrays can store different types of data in the same array

Integer

signed unsigned

Javaclasses

functionhandles

user-definedclasses

Characters and Strings Strings are arrays of characters.

Characters are represented internallyby 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 =A

>> class(c)ans =char

char() creates a character string

>> doc char>> doc class

s is a row vector of 8 characters

>> s = 'ABC DEFG's =ABC DEFG

>> x = double(s)x = 65 66 67 32 68 69 70 71

>> char(x)ans =ABC DEFG

>> size(s)ans = 1 8>> class(s)ans =char

ASCII codes

convert ASCII codes to characters

>> s(2), s(3:5)ans =Bans =C D

Concatenating Strings

s = ['Albert', 'Einstein']s =AlbertEinstein

>> s = ['Albert', ' Einstein']s =Albert Einstein

>> s = ['Albert ', 'Einstein']s =Albert Einstein

>> size(s)ans = 1 15

preserve leading and trailing spaces

>> doc strcat>> doc strvcat>> doc num2str>> doc strcmp>> doc findstr

Concatenating Strings

s = strcat('Albert ', 'Einstein')s =AlbertEinstein

>> s = strcat('Albert', ' Einstein')s =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

Concatenating Vertically

s = ['Apple'; 'IBM'; 'Microsoft'];??? Error using ==> vertcatCAT arguments dimensions are not consistent.

s = ['Apple '; 'IBM '; 'Microsoft']s =Apple IBM Microsoft

>> size(s)ans = 3 9

padded with spaces to the length of the longest string

strvcat,char both pad spaces as necessary

s = strvcat('Apple', 'IBM', 'Microsoft');s = char('Apple', 'IBM', 'Microsoft');

s =Apple IBM Microsoft

>> size(s)ans = 3 9

Concatenating Vertically

Recommendation: use char to concatenate vertically, and [] to concatenate horizontally

s = num2str(A)s = num2str(A, precision)s = num2str(A, format)

num2str a = [143.87, -0.0000325, -7545]';

>> s = num2str(a)s = 143.87-3.25e-005 -7545>> s = num2str(a,4)s = 143.9-3.25e-005 -7545>> s = num2str(a, '%12.6f')s = 143.870000 -0.000032-7545.000000

max number of digits

format spec

num2str a = [143.87, -0.0000325, -7545]';

>> s = num2str(a, '%10.5E')s = 1.43870E+002-3.25000E-005-7.54500E+003

b = char('A', 'BB', 'CCC');

>> disp([b, repmat(' ',3,1), s])A 1.43870E+002BB -3.25000E-005CCC -7.54500E+003

0 5-1

0

1sin(2t)

0 5-1

0

1sin(5t)

0 5-1

0

1sin(8t)

0 5-1

0

1sin(10t)

Labeling and savingmultiple plots with num2str

saved as file1.eps, file2.epsfile3.eps, file4.eps

t = linspace(0,5,101); w = [2,5,8,10]; Y = sin(w'*t); % 4x101 matrixs = 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

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==s1ans = 1 1 1 1 1

>> s1==s2ans = 1 1 1 1 0

>> s1 = 'short'; s2 = 'long';>> s1==s2??? Error using ==> eqMatrix dimensions must agree.

Comparing Strings

>> doc strcmp>> doc strcmpi

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)ans = 0>> s1 = 'short'; s2 = 'long';>> strcmp(s1,s2)ans = 0

case-insensitive

Useful String Functions

sprintf - write formatted stringsscanf - read formatted stringdeblank - remove trailing blanksstrcmp - compare stringsstrcmpi - compare stringsstrmatch - find possible matchesupper - convert to upper caselower - convert to lower caseblanks - string of blanksstrjust - left/right/center justify stringstrtrim - remove leading/trailing spacesstrrep - replace stringsfindstr - find one string within another

Structures Structures have named ‘fields’ that canstore all kinds of data: vectors, matrices,strings, cell arrays, other structures

student.name = 'Apple, A.'; % stringstudent.id = 12345; % numberstudent.exams = [85, 87, 90]; % vectorstudent.grades = {'B+', 'B+', 'A'}; % cell

name.field

>> studentstudent = name: 'Apple, A.' id: 12345 exams: [85 87 90] grades: {'B+' 'B+' 'A'}

>> class(student)ans =struct

structures can also be createdwith struct()

Structure Arrays

student(2).name = 'Twitter, T.';student(3).id = 345678;

add two more students with partially defined fields, rest of fields are still empty

>> studentstudent = 1x3 struct array with fields: name id exams grades

structure array index

Structure Arrays

>> student(1)ans = name: 'Apple, A.' id: 12345 exams: [85 87 90] grades: {'B+' 'B+' 'A'}

>> student(3)ans = name: [] id: 345678 exams: [] grades: []

>> student(2)ans = name: 'Twitter, T.' id: [] exams: [] grades: []

Structure Arrays

>> student(3).exams = [70 80];

>> student(3) ans = name: [] id: 345678 exams: [70 80] grades: []

the missing field values can be defined later and don’t haveto be of the same type or length as those of the other entries

Accessing Structure Elements

>> student(1)ans = name: 'Apple, A.' id: 12345 exams: [85 87 90] 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.contentindexing

s.a = [1 2; 3 4]; s.b = {'a', 'bb'; 'ccc', 'dddd'};>> ss = a: [2x2 double] b: {2x2 cell}

>> s.aans = 1 2 3 4

>> s.a(2,2)ans = 4

>> s.bans = 'a' 'bb' 'ccc' 'dddd'

>> s.b(2,1), s.b{2,1}ans = 'ccc'ans =ccc

cell vs.contentindexing

Nested Structures

student.name = 'Apple, A.';student.id = 12345;student.work.exams = [85, 87, 90];student.work.grades = {'B+', 'B+', 'A'};

>> studentstudent = name: 'Apple, A.' id: 12345 work: [1x1 struct]

>> student.work % sub-structureans = exams: [85 87 90] grades: {'B+' 'B+' 'A'}

Stucture Functions

struct - create structurefieldnames - get structure field namesisstruct - test if a structureisfield - test if a fieldrmfield - remove a structure fieldstruct2cell - convert structure to cell array

>> C = struct2cell(student)C = 'Apple, A.' [ 12345] [1x1 struct]>> C{3}ans = exams: [85 87 90] grades: {'B+' 'B+' 'A'}

content indexing

Cell Arrays 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 ofobjects in curly brackets { }, e.g.,

c = {A, B, C, D}; % 1x4 cell c = {A; B; C; D}; % 4x1 cellc = {A, B; C, D}; % 2x2 cell

where A,B,C,D are arbitrary objects

c{i,j} accesses the data in i,j cellc(i,j) is the cell object in the i,j position

cell vs.contentindexing

A = {'Apple'; 'IBM'; 'Microsoft'}; % cells B = [1 2; 3 4]; % matrixC = @(x) x.^2 + 1; % functionD = [10 20 30 40 50]; % row

c = {A,B;C,D} % define 2x2 cell array

c = {3x1 cell} [2x2 double] @(x)x.^2+1 [1x5 double]

>> cellplot(c);

A = {'Apple'; 'IBM'; 'Microsoft'}A = 'Apple' 'IBM' 'Microsoft'

S = char('Apple', 'IBM', 'Microsoft')S =Apple IBM Microsoft

>> size(A), class(A)ans = 3 1ans =cell

>> size(S), class(S)ans = 3 9ans =char

comparing cell arrays of strings vs. strings

>> A(2), class(A(2))ans = 'IBM'ans =cell

>> A{2}, class(A{2})ans =IBMans =char

>> A'ans = 'Apple' 'IBM' 'Microsoft'

>> S

Apple IBM Microsoft

>> S'

AIMpBipMcl re o s o f t

cell vs.contentindexing

A = {'Apple'; 'IBM'; 'Microsoft'}; % cells B = [1 2; 3 4]; % matrixC = @(x) x.^2 + 1; % functionD = [10 20 30 40 50]; % row

c = {A,B;C,D} % define 2x2 cell array

c = {3x1 cell} [2x2 double] @(x)x.^2+1 [1x5 double]

>> cellplot(c);

>> celldisp(c)

c{1,1}{1} =Applec{1,1}{2} =IBMc{1,1}{3} =Microsoft

c{2,1} = @(x)x.^2+1

c{1,2} = 1 2 3 4

c{2,2} = 10 20 30 40 50

>> c{1,1}ans = 'Apple' 'IBM' 'Microsoft'

>> c{2,1}ans = @(x)x.^2+1

content indexing with { }

0 1 2 30

2

4

6

8

10

>> c{1,1}{3}ans =Microsoft>> c{1,1}{3}(6)ans =s

>> x = [1 2 3];>> c{2,1}(x)ans = 2 5 10

>> fplot(c{2,1},[0,3]);

>> c{1,2}(2,:)ans = 3 4

>> c{1,2}(1,2)ans = 2

>> c{2,2}(3)ans = 30

content indexing with { }

cell indexing ( )content indexing { }>> c(2,2)

ans = [1x5 double]

>> class(c(2,2))ans =cell

>> c{2,2}ans = 10 20 30 40 50

>> class(c{2,2})ans =double

cell

cell contents

>> c{1,1}(2)ans = 'IBM'

>> class(c{1,1}(2))ans =cell

>> c{1,1}{2}ans =IBM

>> class(c{1,1}{2})ans =char

cell

cell contents

cell indexing ( )content indexing { }

>> 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}ans = []

>> cellplot(d);

>> e = reshape(d,3,2)

>> cellplot(e)

>> f = repmat(c,1,2)

>> cellplot(f)

try also

>> f = d';

changing cell array contents

>> c{1,1}{2} = 'Google';>> c{1,2} = 10*c{1,2};>> c{2,2}(3) = 300;>> celldisp(c)c{1,1}{1} =Applec{1,1}{2} =Googlec{1,1}{3} =Microsoftc{2,1} = @(x)x.^2+1c{1,2} = 10 20 30 40c{2,2} = 10 20 300 40 50

could have used:c{1,1}(2) = {'Google'};

why not ?c(1,2) = 10*c(1,2);

why not ?c{2,2}{3} = 300;

num2cellcell2mat

>> A = [1 2; 3 4];

>> C = num2cell(A)

C = [1] [2] [3] [4]

>> B = cell2mat(C)

B = 1 2 3 4

cell2mat converts numerical cell arrays to numbers num2cell converts numerical array to cell array

>> 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 ==> horzcatCAT arguments dimensions are not consistent.

>> [num2cell(A),S] % construct 2x4 cell

ans = [1] [2] 'a' 'bb' [3] [4] 'ccc' 'dddd'

num2cellcell2mat

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 ==> vertcatCAT arguments dimensions are not consistent. C = [S; num2cell(T)] % make all into cells

C = 'January' 'April' 'July' 'October' [ 30] [ 60] [ 80] [ 70]

fprintf(' %-7s %5.2f\n', C{:});

January 30.00 April 60.00 July 80.00 October 70.00

>> class(C)

ans =

cell

>> C(:)

ans =

'January' [30] 'April' [60] 'July' [80] 'October' [70]

read content column-wiseprint it row-wise

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'% [ 30] [ 60] [ 80] [ 70]% [ -10] [ 40] [ 60] [ 50]

fprintf(' T1 T2\n')fprintf('-------------------------\n')fprintf('%-7s %6.2f %6.2f\n',C{:})% fprintf('%-7s %6.2f %6.2f\n',C{:,:})

T1 T2-------------------------January 30.00 -10.00April 60.00 40.00July 80.00 60.00October 70.00 50.00

>> C(:)

ans =

'January' [ 30] [-10] 'April' [ 60] [ 40] 'July' [ 80] [ 60] 'October' [ 70] [ 50]

num2cellfprintf

transposed

content indexing

column vectors

vararginvarargout

% [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; endif Nin==1, th0=varargin{1}; h0=0; g=9.81; endif Nin==2, th0=varargin{1}; ... h0=varargin{2}; g=9.81; endif Nin==3, th0=varargin{1}; ... h0=varargin{2}; g=varargin{3}; end

varargin,varargout are cell arrays that allow the passing a variable number of function inputs & outputs

continues

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; endif nargout==2; varargout{1} = x; ... varargout{2} = y; endif nargout==3; varargout{1} = x; varargout{2} = y; ... varargout{3} = vx; endif nargout==4; varargout{1} = x; ... varargout{2} = y; ... varargout{3} = vx; ... varargout{4} = vy; end

Multidimensional Arrays

A three-dimensional array is a collection oftwo-dimensional matrices of the same size, andare 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.

pages

pj

i

columns

rows applications invideo processing

>> a = [1 2; 3 4];>> A(:,:,1) = a; >> A(:,:,2) = 10*a; >> A(:,:,3) = 100*a;

>> AA(:,:,1) = 1 2 3 4

A(:,:,2) = 10 20 30 40

A(:,:,3) = 100 200 300 400

sum, min, maxcan operate along the i,j,p dimensions

pages

>> sum(A,1)ans(:,:,1) = 4 6ans(:,:,2) = 40 60ans(:,:,3) = 400 600

>> sum(A,2)ans(:,:,1) = 3 7ans(:,:,2) = 30 70ans(:,:,3) = 300 700

>> sum(A,3)ans = 111 222 333 444

A(:,:,1) = 1 2 3 4

A(:,:,2) = 10 20 30 40

A(:,:,3) = 100 200 300 400

>> min(A,[],1)ans(:,:,1) = 1 2ans(:,:,2) = 10 20ans(:,:,3) = 100 200

>> min(A,[],2)ans(:,:,1) = 1 3ans(:,:,2) = 10 30ans(:,:,3) = 100 300

>> min(A,[],3)ans = 1 2 3 4

A(:,:,1) = 1 2 3 4

A(:,:,2) = 10 20 30 40

A(:,:,3) = 100 200 300 400

>> A>20 & A<300ans(:,:,1) = 0 0 0 0ans(:,:,2) = 0 0 1 1ans(:,:,3) = 1 1 0 0>> k = find(A>20 & A<300)k = 6 8 9 11

column-order across pages

A(:,:,1) = 1 2 3 4

A(:,:,2) = 10 20 30 40

A(:,:,3) = 100 200 300 400

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

MATLAB Data Classes

Character

Floating Point

single precision

double precision

Logical Numeric Symbolic Cell Structure

More ClassesSymbolic data types arecreated with sym,syms

Integer

signed unsigned

Javaclasses

functionhandles

user-definedclasses

>> help symbolic>> doc symbolic>> doc sym>> doc syms

>> syms x y z >> syms x y z real>> syms x y z positive

>> x = sym('x');

>> f = x^6-1f =x^6 - 1 >> g = x^3 +1g =x^3 + 1

>> sym(sqrt(2))ans =2^(1/2) >> sqrt(sym(2))ans =2^(1/2) >> double(ans)ans = 1.4142

³1

p 32

p 22 0 ¡ 1

´

>> a = [0, pi/6, pi/4, pi/2, pi];>> cos(a)ans = 1 0.8660 0.7071 0 -1>> c = cos(sym(a))c =[ 1, 3^(1/2)/2, 2^(1/2)/2, 0, -1]

>> symdisp(c)

display symbolic expressionusing LaTeX – on sakai

>> pretty(c) +- -+ | 1/2 1/2 | | 3 2 | | 1, ----, ----, 0, -1 | | 2 2 | +- -+

x6 ¡ 1x3 + 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)

>> f = x^6-1;>> g = x^3 +1;

Functions for factoring and simplification of algebraic expressions:

simplify - Simplifyexpand - Expandfactor - Factorcollect - Collectsimple - Search for shortest formnumden - Numerator and denominatorsubs - Symbolic substitution

>> simplify(r)ans =x^3 - 1 >> factor(simplify(r)) % x^3 - 1ans =(x - 1)*(x^2 + x + 1) >> factor(g) % x^3 + 1ans =(x + 1)*(x^2 - x + 1) >> factor(f) % x^6 - 1ans =(x - 1)*(x + 1)*(x^2 + x + 1)*(x^2 - x + 1)

factor

>> syms x a b; >> expand((x+1)*(x+2))ans =x^2 + 3*x + 2 >> expand(exp(a+b))ans =exp(a)*exp(b) >> expand(cos(a+b))ans =cos(a)*cos(b) - sin(a)*sin(b)

>> expand(cosh(a+b)) ans =sinh(a)*sinh(b) + cosh(a)*cosh(b)

expand

>> A = [sin(2*x), sin(3*x) cos(2*x), cos(3*x)]A =[ sin(2*x), sin(3*x)][ cos(2*x), cos(3*x)] >> 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

collect>> collect((x+1)*(x+2))ans =x^2 + 3*x + 2

>> collect((a+b)*(a^2 + 2*a*b + b^2), a)ans =a^3 + (3*b)*a^2 + (3*b^2)*a + b^3 >> collect((a+b)*(a^2 + 2*a*b + b^2), b)ans =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)ans =(a + b)^3

simplify

>> simplify(a^3 + 3*a^2*b + 3*a*b^2 + b^3)ans =(a + b)^3

>> simplify(cos(b)*sin(a) - cos(a)*sin(b))ans =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)ans =[ sin(2*x), sin(3*x)][ cos(2*x), cos(3*x)]

2x + 3x2 +5 + 1

2x3 + x2 + 10x + 8x2 +5

numden

>> [num,den] = numden(1 + 2*x + 3/(x^2+5)) num =2*x^3 + x^2 + 10*x + 8den = x^2 + 5

>> symdisp(1 + 2*x + 3/(x^2+5))

>> symdisp(num/den)

subs>> syms x a b>> y = a*x+by =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 a,b class double

x,a,b class sym

a,b taken from workspace

Functions for solving algebraic and differential equations:

solve - solve algebraic equations.dsolve - solve differential equations.finverse - Functional inverse.compose - Functional composition.

¡ b+ p b2 ¡ 4ac2a

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 =-(b + (b^2 - 4*a*c)^(1/2))/(2*a)ans =-(b - (b^2 - 4*a*c)^(1/2))/(2*a)

symdisp(xsol(1));

>> g = a*(x-xsol(1))*(x-xsol(2))g =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) + cans = 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)ans = 0

>> 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

some variations 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)ans =- u - z>> solve(w+y+z)ans =- w - z

how does it knowwhich variableto solve for?alphabeticallyclosest 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)

solving equations

>> 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 = -1.6180 0.6180

>> phi = simplify(1./x1)phi = 5^(1/2)/2 + 1/2 1/2 - 5^(1/2)/2

x1 class sym

class double

golden ratio

solving equations

>> 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 =0

>> limit(F/subs(F,n,n-1), n, inf)ans =2/(5^(1/2) - 1)

>> simplify(limit(F/subs(F,n,n-1), n,inf))ans =5^(1/2)/2 + 1/2

Fibonacci numbers, F(n) = F(n-1)+F(n-2) = [0, 1, 1, 2, 3, 5, 8, 13, …]

golden ratio

>> 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)ans = 5^(1/2)/2 - 1/2 - 5^(1/2)/2 - 1/2

>> solve('1/x = x/(1-x)');

solving equations

>> eq1 = 'x^2 + y - 1=0';>> eq2 = 'x+y=0';>> [x,y] = solve(eq1,eq2)

x = 5^(1/2)/2 + 1/2 1/2 - 5^(1/2)/2y = - 5^(1/2)/2 - 1/2 5^(1/2)/2 – 1/2

>> eval(x) % or, double(x)ans = 1.6180 -0.6180

solving equations

>> [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]ans =[ 1, 0][ 0, 1]

solving equations

returned as astructure of syms

>> 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]

linear equations

from homework-9

>> b = [12; -3; 11; 10];

>> x = inv(A)*b % or, A\b x = 1 -2 3 1

>> class(x)ans =sym

linear equations

>> f = 5*x^4 - 2*x^3 + x^2 + 4*x + 3f =5*x^4 - 2*x^3 + x^2 + 4*x + 3

>> p = sym2poly(f)p = 5 -2 1 4 3

>> poly2sym(p)ans =5*x^4 - 2*x^3 + x^2 + 4*x + 3

>> poly2sym(p,'t')ans =5*t^4 - 2*t^3 + t^2 + 4*t + 3

polynomials

poly2symsym2polycoeffsquorem

rootspoly

>> [q,mono] = coeffs(f)q =[ 5, -2, 1, 4, 3]mono =[ x^4, x^3, x^2, x, 1]

>> p = sym2poly(f)p = 5 -2 1 4 3

>> z = roots(p)z = 0.7393 + 0.8967i 0.7393 - 0.8967i -0.5393 + 0.3916i -0.5393 - 0.3916i

polynomials

poly2symsym2polycoeffsquorem

rootspoly

>> p = sym2poly(f)p = 5 -2 1 4 3

>> z = roots(p)z = 0.7393 + 0.8967i 0.7393 - 0.8967i -0.5393 + 0.3916i -0.5393 - 0.3916i

>> P = poly(z)P = 1.0 -0.4 0.2 0.8 0.6>> 5*Pans = 5 -2 1 4 3

polynomials

poly2symsym2polycoeffsquorem

rootspoly

-1 -0.5 0 0.5 10

2

4

6

8

10

12

x

f(x)

>> 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)');

>> syms n

>> symsum(1/n^2, n, 1, inf)ans =pi^2/6

>> symsum(1/n^4, n, 1, inf)ans =pi^4/90

symsum

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)ans =(N*(2*N + 1)*(N + 1))/6

finite & infinitegeometric series

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)ans =x^3/6 + x^2/2 + x + 1

>> taylor(sin(x),4)ans =x - x^3/6

>> taylor(sin(x)/x)ans =x^4/120 - x^2/6 + 1

cos³ ¼cos(x)

x

limits>> syms x

>> limit(exp(-x), x, inf)ans =0

>> limit(sin(x)/x, x, 0)ans =1

>> limit(cos(pi*cos(x)/2)/x, x, 0)ans =0 >> taylor(cos(pi*cos(x)/2)/x,2)ans =(pi*x)/4

simple calculus

differentiationintegration

>> syms x

>> diff(x^2)ans = 2*x >> diff(x^3)ans =3*x^2

>> diff(cos(x))ans-sin(x)

>> syms x

>> int(x^2)ans = x^3/3 >> int(cos(x))ans =sin(x)

>> int(cos(x)^2, 0, pi)ans =pi/2

dsolveaccelerationwith air drag

terminal velocityand time constant

solve with initialvelocity v(0) = v0

exact solution

dsolveD = 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)v =va^2/v0 + (va*(v0^2 - va^2))/(v0*(va + v0*tanh(t/ta)))

>> [num,den] = numden(v);

tanh¡ tta

¢ va2 + v0vava+ v0 tanh¡ t

ta¢

dsolve>> v = num/denv =(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 =0

0 10 20 300

10

20

30

t

v(t)

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)');

0 10 20 300

10

20

30

t

v(t)

dsolvev0 = 0; va = 30; ta = 10; tspan = [0,30];

vdot = @(t,v) va/ta * (1 - v.^2/va^2);

[t2,v2] = ode45(vdot, tspan, v0);

plot(t2,v2,'r-')xlabel('t');ylabel('v(t)');

compare exact andnumerical solutionsusing ode45

dsolvecompare exact and numerical solutions using forward Euler method, which replaces derivatives by forward differences

0 10 20 300

10

20

30

t

v(t)

exact numerical

dsolveTspan = 30; N = 60; T = Tspan/N;tn = 0:T:Tspan; % tn = 0:0.5:30vn(1) = v0;for n=1:N, vn(n+1) = vn(n) + T*va/ta*(1-vn(n)^2/va^2);endplot(t1,v1,'b'); hold on;plot(tn,vn,'r--')

compare exact andnumerical solutionsusing forward Euler

Recommended