Notes On MATLAB
Notes On MATLAB
Steven J. Frank
Commands
May be terminated with a semicolon, which suppresses output
Math functions
Vectors
Collection of numbers arranged in a single row or a single column
Row vector: vRow = [3, -2, 0, 5]
Column vector: vCol = [3; -2; 0; 5]
Length function:
o Vector: L1 = length(u) scalar output equal to number of elements in
the vector
o Matrix: L2 = length(m) max(# of rows, # of cols)
Size function: get number of rows and number of columns in a matrix
o s1 = size(u)
o Returns two-element row vector; first element is number of rows,
second element is number of columns
o will tell you whether an array is a matrix, a row vector or a column
vector
Matching sizes of vectors and scalars
o If know which vector is bigger, can use: v = v*ones(size(v bigger))
o To make a constant, c, the same size as a vector, v: c = c + 0*v
Transposing vectors
o Row column vector
o Enter single quotation mark after variable name
c = v
Vector indexing
o Index of first element = 1
o a = v(4) assigns fourth element of vector v to variable a
o Replacing value: v(4) = 6
o Adding new value: v(n) = 6 where length of vector is n1
Uniformly spaced vectors
Matrices
Matrix creation
Matrix concatenation
o Concatenate matrices A, B:
C = [A, B] horizontal concatenation
C = [A; B] vertical concatenation
Array-creation functions
Row/column indexing
Example:
Plotting
Example
% First we choose some numerical values for plotting limits, here L and t_0.
% Here we'll use:
L = 3;
t_0 = 8;
% Create the (numerical) vector for position along the shaft, Num_x:
Num_x = linspace(0,L);
% The corresponding vector for the applied torque is, from the problem
% statement:
Num_t_x = t_0*(1 - Num_x/L);
% The expression to compute the (numerical) vector Num_T
% in terms of Num_x is:
Num_T = (t_0*(L - Num_x).^2)/(2*L); %Note use of power expression .^
% Finally, we create subplots (so we can have both curves on the same
% figure) and make area plots of Num_t_x and Num_T vs. the Num_x:
subplot(2,1,1)
area(Num_x, Num_t_x, 'LineWidth', 2.0, 'FaceColor', [0.,0.9,0.9])
xlabel('x')
ylabel('t_x(x)')
subplot(2,1,2)
area(Num_x, Num_T, 'LineWidth', 2.0, 'FaceColor', [0.9,0.0,0.9])
xlabel('x')
ylabel('T(x)')
ezplot(fun) plots the expression fun(x) over the default domain -2 < x < 2, where fun(x) is
10
Plotting an area
From E7_2
See discontinuities discussion below
L = 1;
P = 1000;
x1 = linspace(0,2*L);
x2 = linspace(2*L,3*L);
x3 = linspace(3*L,4*L);
M1 = -x1*P;
M2 = -(4*L-x2)*P;
M3 = -L*P+0*x3;
x = [x1,x2,x3];
M = [M1,M2,M3];
area(x,M,'LineWidth', 2.0, 'FaceColor', [0.9,0.9,0.9])
xlabel('x')
ylabel('M(x)')
11
Plotting a surface
From E6_1_2X
x=linspace(0,L,20);
RA = sqrt(2)*R0;
RB = sqrt(5)*R0;
R=RA+(RB-RA)*x/L;
Gc=2*G0;
Gs=G0;
Ipc=pi*R0^4/2;
Ips=pi*(R.^4-R0^4)/2 ;
12
Discontinuities
a = 0.01; b = 0.005; L = 3;
x1 = linspace(0,L/3);
x2 = linspace(L/3,L);
u1 = -a + 0*x1;
u2 = 3*a + (-b^2/a)*x2.^2;
x = [x1,x2];
u = [u1,u2];
area(x,u,'LineWidth', 2.0, 'FaceColor', [0.,0.9,0.9])
xlabel('x')
ylabel('u(x)')
13
14
the
the
the
the
function to be integrated,
variable of integration,
lower bound, and
upper bound.
Note that we're using the variable xp to represent our variable of integration, x.
% Create symbolic variables representing the quantities
% used in the problem with the "syms" command:
syms L epsilon_0 x xp;
% Now, create a symbolic function for epsilon_a(x).
% Variables created by manipulating other symbolic
% variables are automatically classified as symbolic:
epsilon_a(xp) = epsilon_0 * (1 - xp/L)
%
%
%
%
15
% the last two are the lower and upper bounds of integration.
u_x(x) = 0 + int(epsilon_a(xp), xp, 0, x)
% Finally, find the elongation by taking the difference of
% the displacement at L and the displacement at 0:
delta = u_x(L) - u_x(0)
% Alternatively, you can directly evaluate the elongation
% with the equivalent definite integral:
delta = int(epsilon_a(xp), xp, 0, L)
Characterizing variables
Declaration
o syms L P A_0 E x xp
Assignment of values
o a = 10, b = 20, c = 25
% because MATLAB in general assumes that variables are complex...
syms L P A_0 E x xp real;
% ...it is a good idea to tell MATLAB that they are real
% It is also a good idea to give physical bounds for the variables
assumeAlso(x>0); % and that x>0...
assumeAlso(L>0); % and that L>0..
assumeAlso(L>x); % and that L>x...
%generally, doing this helps MATLAB find the
%right branch of the solution, avoiding piecewise functions
% You can also ask MATLAB to do some algebraic simplification work for you!
% the "simple" MATLAB function used below, runs the expression through a series
% of simplification steps, and returns the "most simplified" form of the function.
nice_u_x(x)= simple(u_x(x))
Solving an equation
We can use the "solve" function to solve
do so by hand. Note that we must use the
equation we want to solve; this is *not*
instead of creating a symbolic equation,
to overwrite whatever is stored in "uxB"
16
17
18
19
Example
Second-order ODE: 2
entries in column vector,
dx/dt (as in previous
example) and d2x/dt2
defined in terms of the
expression for dx/dt and x.
20
=
=
=
=
x
dx/dt
y
dy/dt
In this example we define u as x(1) for use in column vector dx, which defines the
ODE function (i.e., the right-hand side of the state equation). x_init is defined and
then called in ODE function.
21
The matrix x returned from ode45 has columns corresponding to the state variables,
while the rows correspond to the values of the state variables at the corresponding
time points given in t. Hence, to get all the values from the first column of x
(corresponding to the first state variable x(1)), use x(:,1).
22
PSet 1/Problem 5
function main()
% Define initial conditions in [rad] and [rad/s]
x1_init = 0; % [rad]
x2_init = 0.5; % [rad/s]
x_init = [x1_init;
x2_init];
% Define the time interval in [seconds]
tSpan = [0,4]; % Solve for time = 0 to time = 4 [sec]
% ODE Solver:
[t,x] = ode45(@StateEqn,tSpan,x_init);
% Plot Output
plot(t,x,'o-')
legend('x_1','x_2')
%Format plot
set(gca,'FontSize',16)
xlabel('Time (sec)','FontSize',16)
ylabel('Position (rad), Velocity (rad/s)','FontSize',16)
title('Solutions to ODE','Fontsize',16)
end
% Subfunction StateEqn:
function dxdt = StateEqn(t,x)
% Constants
g = 9.81; % [m/s^2]
L = 1; % [m]
% Define right-hand-side of dxdt = f(t,x)
dxdt = zeros(2,1); % Make sure it's a column vector
dxdt(1) = x(2);
dxdt(2) = -g/L*sin(x(1));
end
23
PSet 2/Problem 6
function main()
% Initial velocity and angle
v_init = 100; % [m/s]
theta = 50; % [deg]
% NOTE: MATLAB trigonometric operations take radians!
theta = theta/180*pi;
% DEFINE INITIAL CONDITION STATE VECTOR IN [m] AND [m/s]
x1_init = 0
x2_init = 64.28 % 100cos(50)
x3_init = 0
x4_init = 76.6 % 100sin(50)
x_init = [x1_init; x2_init; x3_init; x4_init];
% State vector = col. with x(1) = x, x(2) = dx/dt, x(3) = y, x(4) = dy/dt
% DEFINE THE TIME INTERVAL IN [s]
tSpan = [0,7]
% ODE Solver:
[t,x] = ode45(@StateEqn,tSpan,x_init);
% PLOT THE TRAJECTORY (HEIGHT VS RANGE).
% NOTE THAT THE x ABOVE IS A MATRIX IN WHICH THE COLUMNS
% CONTAIN THE VALUES OF RANGE, X-VELOCITY, HEIGHT, AND Y-VELOCITY
plot(x(:,1),x(:,3)) % This is the syntax to plot x(1), x(3)
xlabel('Range [m]')
ylabel('Height [m]')
end
% Subfunction StateEqn:
function dxdt = StateEqn(t,x)
% Constants
m = 0.034; % [kg]
g = 9.81; % [m/s^2]
c = 0.00078; % [N-s^2/m^2]
%
%
%
%
DEFINE THE RIGHT HAND SIDE OF THE STATE EQUATION dxdt = F(t,x)
NOTE: dxdt should be a column vector containting 4 elements.
Here, x is a state-vector containing 4 quantities representing:
range (x position), x-velocity, height (y position), y-velocity
vx = x(2)
vy = x(4)
dxdt = zeros(4,1);
dxdt(1) = vx;
dxdt(2) = -(c/m)*(sqrt(vx^2+vy^2))*vx;
dxdt(3) = vy;
dxdt(4) = -g-(c/m)*sqrt((vx^2)+(vy^2))*vy;
end
24
APPENDIX
25
26