E154 V.
Khayms
Introduction to Engineering Fall 2003
Mathematics
MATLAB Tutorial, Part 2
1. Plotting in 3D 2. Creating a simple script
Plotting parametric curves a) Open new .m file
b) Type in commands
>> t=0:0.1:4*pi;
>> x=cos(t); % Creating a plot
>> y=sin(t); clear;
>> z=t; x=linspace(0,15,1000);
>> plot3(x,y,z); y=sin(x).*x;
>> grid on plot(x,y)
grid on
c) Save file as
plot_demo1.m
d) Execute script:
>> plot_demo1
Plotting surfaces
>> [x,y]=meshgrid(-2:0.1:2,-2:0.1:2);
>> z=sin(x.^2+y.^2);
>> surface(x,y,z)
>> shading('interp');
>> grid on 3. Creating a function
>> colorbar
a) Open new .m file
b) Type in commands
% This function computes dot
% product of vectors a and b
function [ans]=dot_product(a,b)
ans=a(1)*b(1)+a(2)*b(2)+a(3)*b(3);
c) Save file as for i=1:n
dot_product.m product=product*i;
d) Execute function: end
>> a=[1 2 3]; % This function computes the value
>> b=[2 3 4]; % of n factorial using while loop
>> [ans]=dot_product(a,b)
function [product]=factorial2(n)
ans = product=1;
i=1;
20 while i<=n
product=product*i;
4. Using functions i=i+1;
end
a) Open new .m file
b) Type in commands
% This function computes the value
% This script uses the dot_product % of n factorial using if statements
% function
function [product]=factorial3(n)
clear; product=1;
a=[1 2 3]; i=1;
b=[2 3 4]; while (1)
c=dot_product(a,b) product=product*i;
proj_a_onto_b=c/norm(b) i=i+1;
if i>n
c) Save file as projection.m break
d) Execute script end
end
>> projection
c=
20
proj_a_onto_b =
3.7139
5. Programming in MATLAB
% This function computes the value
% of n factorial using for loop
function [product]=factorial1(n)
product=1;