Вы находитесь на странице: 1из 26

# MATLAB NOTES

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

## Syntax is: first value:spacing:last value

When spacing between values is one, need not say y = 2:1:7 ; instead
can say y = 2:7
o To define by number of intervening vectors, use
X=linspace(1.4,5.2,4)to create a vector with end values 1.4 and 5.2,
and 4 intervening values
Vector arithmetic: if v is a vector,
o b = a*v multiplies each value of v by the scalar a
o To add the same value to each vector element, set up a new vector of
the same size with the desired value as each element, and add vectors
Or: to add value a, can say: c = v + a*ones(size(v))
But easiest to simply say: c = v + a, and Matlab expands a into
a vector of as of the proper size to match v, and adds on an
element-by-element basis
o To assign the same value a to each element of a vector v,
u = a*ones(size(v))
u = a + 0*v
o Element-wise operations (see Appendix)
Exponents: v.^2 raises each element of vector v to second
power
Multiplication: v.*a (where a is a scalar value)
Division: v./a (or a./v if vector is the denominator)
Element-wise division needs the period, so if you need to
define a vector y = 1/x where you want to obtain each
element of y as the inverse of the corresponding element
of x, you need to write y = 1./x
o
o

## Inner and outer products

Inner product: multiply row vector by column vector
o If either vector doesnt have the right orientation, perform transpose
o Matrix multiplication operator: *
o If have two row vectors a and b, can multiply as: a * b
Outer product: multiply column vector by row vector

Matrices

Matrix creation

## Matrix multiplication: use * operator

Matrix concatenation
o Concatenate matrices A, B:
C = [A, B] horizontal concatenation
C = [A; B] vertical concatenation

Array-creation functions

Row/column indexing

## Solving systems of Linear Equations

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 (see summary here)

ezplot(fun) plots the expression fun(x) over the default domain -2 < x < 2, where fun(x) is

## an explicit function of only x.

ezplot(fun,[xmin,xmax]) plots fun(x) over the domain: xmin < x < xmax.

## Another plotting example (note use of . for element-wise operation):

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 ;

## % a vector of (20) x positions along the shaft

% a vector with outer radius of the shaft at each x position
% shear modulus of the core
% shear modulus of the sleeve
% Ip of core (constant along the shaft)
% a vector of Ip of sleeve at each x (R is a vector,
% hence .^ is needed)
GIp_eff=Gc*Ipc+Gs*Ips; % a vector of (GIp)_eff at each section x
dphi_dx=T./GIp_eff;
% a vector of dphi/dx at each section x
gamma_max=100*R.*dphi_dx; % (multiply by 100 to get % and use .* as both are
% vectors)
theta=linspace(0,2*pi,20); % a vector of (20) angle positions around the shaft
[R_g,theta_g]=meshgrid(R,theta); % a grid of (R,theta) positions on the surface
% of the shaft
[x_g,dummy]=meshgrid(x,theta);
% corresponding x positions for each grid point
[gamma_g,dummy]=meshgrid(gamma_max,theta); %corresponding shear strains on each grid
%point
y_g=R_g.*cos(theta_g);
% get y and z position for each grid point
z_g=R_g.*sin(theta_g);
% need .* because we multiply elements of 2 arrays
surf(x_g, y_g, z_g, gamma_g)
%plot the grid with color given by % strain
xlabel('position along shaft [m]')
ylabel('y [m]')
zlabel('z [m]')
cb=colorbar ;
% create a colorbar for the contour levels
ylabel(cb,'shear strain [%]') % label the colorbar

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

## Example: using the int MATLAB function to perform symbolic integration

The arguments of the int function are:
1.
2.
3.
4.

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

## Use symbolic integration to obtain the axial displacement

fields. The int function computes the (symbolic) integral
of a symbolic function; the first input is the expression
to integrate, the second is the independent variable, and

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"

## for RxB symbolically if we prefer not to

equality operator "==" to define the
the same as the assignment operator "=";
writing uxB = 0 would instead tell MATLAB
with the number zero!

## Another example: (L*(3*Ra - L*p_0))/(9*A*E) + (2*L*(9*Ra - 2*L*p_0))/(27*A*E),

and we want to solve for Ra
syms N1 N2 p_0 x xp L ea1 ea2 Ra ux E A;

16

## Solving for a value and defining variables

y = -(p_0*x*(28*L^2 - 54*L*x + 27*x^2))/(108*A*E*L), x=.705, L=2, E=200e9, A=200e-6,
p_0 = 200e3

17

## For first-order ODE,

function column
vector has only one
entry: the expression
for dx/dt

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

## The initial state variables have a fixed format as a column vector:

x(1)
x(2)
x(3)
x(4)

=
=
=
=

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