ME18A - MATLAB Lecture Notes
ME18A - MATLAB Lecture Notes
To add comments to MATLAB code, use percent (%) symbol - green color
x = input(prompt) - displays the text in prompt and waits for the user
to input a value and press return/enter key.
Ex:
prompt = “what is the value?”;
x = input(prompt) % can enter any number
y = x*10
Ex:
width = input (‘Enter the width:’)
len = input (‘Enter the length:’);
% width = 5;
% len = 10.2;
area = len*width; % This computes the area of a rectangle
fprintf(‘The area of the rectangle with length %f and width %f is
%f \n’,len,width,area);
Lecture 2
difference =
0.5000
Array
A = [ 4 5 3 7 9 11]; % array
B = A; % make copy of A
len = length(A); % how many elements are in A
A1 = A(1:4); % create a new array A1 with the first 4 elements of A
A2 = A(end-3: end); % create a new array A2 with the last 4 elements
of A
A3 = [A1 A2]; % concatenate A1 and A2
A(3) = 13 % replace the third element by 13
x = min(A); % determine the minimum number in the array
[y,i] = max(A); % determine the max number in the array
A(1:3) = [ ]; % Remove the first 3 elements from the array
Ex:
A = 5:2:100; % create an array A with the lowest number 5 and the
highest number 100 in steps of 2
B = 100: -2: 5; % create an array A with the highest number 100
and the lowest number 5 in steps of -2
C = 5: -2: 100; % result will be zero (empty row)
D = 100: 2: 5; % result will be zero (empty row)
Ex:
Y = linspace(100, 5, 1000); % 100 to 5 with 1000 values in
between
Lecture 3
Ex:
subplot(2,1,1);
x=linspace(0,10);
y1=sin(x);
plot(x,y1)
subplot(2,1,2);
y2=sin(5*x);
plot(x,y2)
Ex:
subplot(2,2,1)
x=linspace(0,10);
y1=sin(x);
plot(x,y1)
title(‘Subplot 1: sin(x)’)
subplot(2,2,2)
y2=sin(2*x);
plot(x,y2)
title(‘Subplot 2: sin(2x)’)
subplot(2,2,3)
y3=sin(4*x);
plot(x,y3)
title(‘Subplot 3: sin(4x)’)
subplot(2,2,4)
y4=sin(8*x);
plot(x,y4)
title(‘Subplot 4: sin(8x)’)
Ex:
subplot(2,2,1);
x=linspace(-2,2,50)
y1=x.^2
plot(x,y1)
hold on;
subplot(2,2,2);
y2=sin(x);
plot(x,y2,’--’);
grid on;
3D Plot Ex:
x=1:1:10;
y=x.^2;
z=x+y
plot3(x,y,z)
Ex:
subplot(2,2,1);
x=linspace(-3.8,3.8);
y_cos=cos(x);
plot(x,y_cos);
title(‘Subplot 1: Cosine’)
subplot(2,2,2);
y_poly=1-x.^2/2 + x.^4./24;
plot(x,y_poly,’g’)
title(‘Subplot 2: Polynomial’)
subplot(2,2,[3,4]);
plot(x,y_cos,’b’,x,y_poly,’g’);
title(‘Subplot 3 and 4: Both’)
Diary - Log command window text to file
Diary myDiaryfile %write any code
diary off
*type myDiaryfile* - calls back what was written in the diary
diary off % to close
Lecture 4
Ex (Basic):
for = i=1:5
i % display vector i individually
end
Ex (Basic):
x=-2:2;
for i=1:length(x)
x(i)
end
Ex: Loop through the matrix and assign each element a new value.
Assign 2 on the main diagonal, -1 on the adjacent diagonal and 0
everywhere else.
nrows=4;
ncols=6;
A=ones(nrows,ncols)
for c=1:ncols
for r=1:nrows
if r==c
A(r,c)=2;
elseif abs(r-c)==1
A(r,c)=-1;
else
A(r,c)=0;
end
end
end
A
function [m,s]=stat(x)
n=length(x);
m=sum(x)/n;
s=sqrt(sum((x-m).^2/n));
end
function [m,s]=stat2(x)
n=length(x);
m=avg(x,n);
s=sqrt(sum((x-m).^2/n));
end
Ex:
inputTemp = input(‘Enter temperature to convert:’);
selection = input(‘Enter 1 to convert to Farenheit and 2 to convert to
Celsius:’)
function outTemp=converceltoFahr(inTemp)
outTemp = 9/5*inTemp + 32;
end
function outTemp=convertFahrtoCel(inTemp)
outTemp=5/9*(inTemp - 32);
end
% Final answer:
n! = 3628800
Ex:
x=[2 43 6 8 1 47 34];
nx=length(x);
acc=0;
counter 1;
while counter <= nx
acc=acc+x*counter; % Add/accumulate
counter=counter+1;
end
Ex:
Lecture 5
Ex:
function y = quad1(x)
y=x.^2-3*x+2;
end
% Use fzero to compute the root using an external file
initial_guess=3; % start from 3 and look around 3 until root is found
x1=fzero(@quad1,initial_guess);
% Using anonymous functions
f=@(x) x.^2-3*x+2; %f is the function handle
x2=fzero(f,initial_guess);
f1=@(x) x.^2.*sin(x)-3*x+2;
x3=fzero(f1,0);
x=linspace(-2,2);
plot(x,f1(x));
grid on;
Ex:
fun=@sin; % function
x0=3; % initial point
x=fzero(fun,x0)
x=
3.1416
fun=@cos; % function
x0=[1 2]; % initial interval
x=fzero(fun,x0)
x=
1.5708
fun=@f; % function
x0=2; % initial point
z=fzero(fun,x0)
z=
2.0946
Lecture 6
T=taylor(sin(x))
T=X-(X^3)/6 + (x^5)/102
Code:
y=sin(x);
y1=x;
y2=x-(x^3)/factorial(3);
y3=x-(x^3)/factorial(3) + (x^5)/factorial(5)
function er = computeError(estimate, actual)
er=abs((estimate - actual)/actual;
end
To call function:
cy1=computeError(y1, y)*100;
cy2=computeError(y2, y)*100;
cy3=computeError(y3, y)*100;
Logical
Syntax: AND—-> &&
Ex: (x>1) && (x<10)
Syntax: OR —-> ||
Ex: (x>1) || (x<-1)
Inequality A~=B % A is not equal to B
OR,|| - Logical OR
Syntax:
expr1 || expr2 - represents a logical OR operation. Expr2 is not
evaluated if expr1 is logical 1 (true). Each expression must evaluate
to a scalar logical result
Lecture 9-10
Matrices
A matrix is a rectangular array of numbers enclosed in brackets, which
are the elements of the matrix
● A has two rows and three columns, it’s a 2x3 matrix.
● B has three rows and three columns, it’s a 3x3 matrix.
𝑡ℎ 𝑡ℎ
● A=[A𝑖𝑗 ], where A𝑖𝑗 is the element in the 𝑖 row and the 𝑗 column.
Matrix Operations
● Equality of matrices: two matrices A and B are equal iff they
have the same elements (i.e. 𝐴𝑖𝑗 = 𝐵𝑖𝑗 for all i and j, basically
copy of each other)
○ For matrices to be equal, they must have the same size
● Transpose: the transpose of matrix A = [𝐴𝑖𝑗 ] is
𝑀𝑖 , 𝑗 is determinant
Determinants
● A determinant of order n is a scalar associated with a n x n
matrix
1. n=1: matrix A is simply a scalar, the determinant equals the
scalar
2. n=2:
3. n=3:
4. n=4:
Inverse
Dot Product:
Vector on matlab:
Cross Product:
MATLAB Translation
Vector Addition Ex:
function c = myAddVectors(a,b)
% a=[1 2 3]; a=i+2j+3k
% b=[4 5 6]; b=4i+5j+6k
% a+b=
[5 7 9]---->5i+7j+9k
if length(a)==length(b)
c(1)=a(1)+b(1) % call function c
C(2)=a(2)+b(2)
c(3)=a(3)+b(3)
else c=[] % return an empty vector
disp(‘Vector lengths are not equal’)
end
Minor Ex:
function[status,minor]=computeMinor(A,r,c) % A-matrix, r-row, c-column
[nr,nc]=size(A)
if (r<=0||c<=0||r>nr||c>nc)
status=-1; % -1 for not valid
else
status=1;
A(r,:)=[]; % removes row r regardless of the column number
A(:,c)=[]; % removes column c
minor=det(A) % determinant of A
end
end
Cofactor Ex:
function [status,cofactor]=computeCofactor(A,r,c)
[status,minor]=computeMinor(A,r,c)
cofactor=((-1)^(r+c)).*minor;
end
Determinant Ex:
function [status,a]=computeDeterminant(a1)
[nr,nc]=size(a1);
if nr ~=nc
status=-1;
a=0;
else
a=det(a1);
status=1;
end
end
Matrix Multiplication Ex:
function[status,a]=multiplyMatrices(a1,a2)
[nr1,nc1]=size(a1);
[nr2,nc2]=size(a2);
if nc1~=nr2 % the # of rows and columns of must be the same
status=0;
a=[];
else
a=a1*a2;
status=1;
end
Lab 4 Problem 2:
function[f,Re]=computeFrictionFactor(V,pipe,fluid)
D=pipe(1);
eps=pipe(2);
rho=fluid(1);
mu=fluid(2);
Re=rho*V*D/mu;
if Re<2000
f=64/Re;
elseif Re>4000
g=@(x) 1/sqrt(x)+2*log10(eps/(3.7*D)+2.51/(Re*sqrt(x)));
f=fzero(g,0.1);
else
f=-1;
end
end
Lecture 11-13
Ex:
A = [1 1 3; 2 0 4; -1 6 -1];
B = [2 19 8];
x = B/A
x = 1x3
Ex:
A = [1 2 0; 0 4 3];
B = [8; 18];
x = A\B
X = 3x1
0
4.0000
0.6667
Ex: Lab 6
lu - LU matrix factorization
Syntax:
[L,U] = lu(A)
Factorizes the full or sparse matrix A into an upper triangular matrix
U and a permuted lower triangular matrix L such that A = L*U
Ex:
Lecture 14
Forward Substitution:
Consider Ax=b (A is the lower triangular matrix—--nonzero elements)
[a11 0… 0 ][x1] [b1]
[a21 a22… 0 ][x2] = [b2]
… …
[am1 am2… amm][xm] [bm]
Ex:
function x = forwardsub(A,b)
[nr,nc]=size(A)
for i=1:nr
x(i)=b(i);
for j=1:i-1
x(i)=x(i)-A(i,j)*x(j);
end
x(i)=x(i)/A(i,i);
end
—---------------------------------------------------------------
When i=1
x(1)=b(1)
j+1:0 —--> no counting, no loop (x1=b1/a11)
x(1)=x(1)/A(1,1)
—----------------------------------------------------------------
When i=2
x(2)=b(2)
j=1:1
x(2)=x(2)-A(2,1)*x(1)
x(2)=x(2)/A(2,2)
—-----------------------------------------------------------------
When i=3
x(3)=b(3)
i=1:2
x(3)=x(3)-A(3,1)*x(1)-A(3,2)*x(2)
x(3)=x(3)/A(3,3)
Backward Substitution:
Consider Ax=b (A is an upper triangular matrix)
xm=bm/amm
Ex:
function x = backsub(A,Y)
[nr,nc]=size(A);
for i=nr:-1:1
x(i)=Y(i);
for j=i+1:nr
x(i)=x(i)-A(i,j)*x(j);
end
x(i)=x(i)/A(i,i)
End
Lecture 15-16
Ex:
→ 4 is the largest absolute value in 1st column of A
A = [-1 5 -2]
[ 3 0 -6]
[ 4 -2 7]
→ Set P to an identity matrix
P = [ 1 0 0]
[ 0 1 0]
[ 0 0 1]
P x A = A
→ Search 2nd column for largest abs val excluding a12: 9/2
→ Switch row 3 with 2:
[4 -2 7]
[0 9/2 1/4]
[0 3/2 -45/4]
Ex:
A = [3 -2 5]
[-5 1 -4]
[5 -6 0]
P = [1 0 0]
[0 1 0]
[0 0 1]
P = [0 1 0] R1=R2
[1 0 0] R2=R1
[0 0 1]
P * A = A
Gaussian Elim:
[-5 1 -4]
R2=R2-(-⅗)R1 [0 -7/5 13/5]
R3=R3-(-1)R1 [0 -5 -4]
P = [0 1 0]
[0 0 1]
[1 0 0]
L = [1 0 0] → L = [1 0 0]
[0 1 0] [-1 1 0]
[0 0 1] [-3/5 -7/25 1]
Matlab Ex:
Lecture 17-20
Interpolation
The goal is to find a polynomial curve that passes through a set of
points; three common types:
● Naive Interpolation
○ Does not give a smooth curve depending on how big the order
is
○ Goes through the points but don’t know what happens in
between
Fit a curve:
2 𝑛
y = 𝑎0 + 𝑎1𝑥 + 𝑎2 𝑥 +... + 𝑎𝑛𝑥