Top Banner
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 1
34

Notes on MATLAB

Dec 06, 2015

Download

Documents

SVR07

Some notes
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Notes on MATLAB

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 vectoro Matrix: L2 = length(m) max(# of rows, # of cols)

Size function: get number of rows and number of columns in a matrixo s1 = size(u)o Returns two-element row vector; first element is number of rows, second element is

number of columnso will tell you whether an array is a matrix, a row vector or a column vector

Matching sizes of vectors and scalarso If know which vector is bigger, can use: v = v*ones(size(vbigger))o To make a constant, c, the same size as a vector, v: c = c + 0*v

Transposing vectorso Row column vector

1

Page 2: Notes on MATLAB

o Enter single quotation mark after variable name c = v’

Vector indexingo Index of first element = 1o a = v(4) assigns fourth element of vector v to variable ao Replacing value: v(4) = 6o Adding new value: v(n) = 6 where length of vector is n–1

Uniformly spaced vectors

o Syntax is: first value:spacing:last valueo When spacing between values is one, need not say y = 2:1:7 ; instead can say y = 2:7o 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 ao 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 a’s of

the proper size to match v, and adds on an element-by-element basiso 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

Inner and outer products Inner product: multiply row vector by column vector

o If either vector doesn’t have the right orientation, perform transposeo 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

2

Page 3: Notes on MATLAB

Matrices

Matrix creation

o Matrix of ones: 2×2 matries of ones = ones(2,2) or ones(2)

3

Page 4: Notes on MATLAB

Matrix multiplication: use * operator

Matrix concatenationo Concatenate matrices A, B:

C = [A, B] horizontal concatenation C = [A; B] vertical concatenation

Array-creation functions

4

Page 5: Notes on MATLAB

5

Page 6: Notes on MATLAB

Row/column indexing

Solving systems of Linear Equations

6

Page 7: Notes on MATLAB

Example:

7

Page 8: Notes on MATLAB

Plotting

8

Page 9: Notes on MATLAB

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.

9

Page 10: Notes on MATLAB

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

10

Page 11: Notes on MATLAB

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

Page 12: Notes on MATLAB

Plotting a surface

From E6_1_2X

x=linspace(0,L,20); % a vector of (20) x positions along the shaftRA = sqrt(2)*R0; %outer radius at ARB = sqrt(5)*R0; %outer radius at B R=RA+(RB-RA)*x/L; % a vector with outer radius of the shaft at each x positionGc=2*G0; % shear modulus of the coreGs=G0; % shear modulus of the sleeveIpc=pi*R0^4/2; % Ip of core (constant along the shaft)Ips=pi*(R.^4-R0^4)/2 ; % 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 xgamma_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

%pointy_g=R_g.*cos(theta_g); % get y and z position for each grid pointz_g=R_g.*sin(theta_g); % need .* because we multiply elements of 2 arrayssurf(x_g, y_g, z_g, gamma_g) %plot the grid with color given by % strainxlabel('position along shaft [m]')ylabel('y [m]')zlabel('z [m]')cb=colorbar ; % create a colorbar for the contour levelsylabel(cb,'shear strain [%]') % label the colorbar

12

Page 13: Notes on MATLAB

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

Page 14: Notes on MATLAB

Analytical Solutions in Matlab

Want x, g to represent symbolic variables, integration done analytically:

To find f for a given value of x, use subs function:

To obtain a numeric approximation, use eval function:

14

Page 15: Notes on MATLAB

Symbolic math toolbox:

Example: using the int MATLAB function to perform symbolic integration

The arguments of the int function are:

1. the function to be integrated,2. the variable of integration,3. the lower bound, and4. the 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

15

Page 16: Notes on MATLAB

% to integrate, the second is the independent variable, and% 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

Declarationo syms L P A_0 E x xp

Assignment of valueso 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 for RxB symbolically if we prefer not to do so by hand. Note that we must use the equality operator "==" to define the equation we want to solve; this is *not* the same as the assignment operator "="; instead of creating a symbolic equation, writing uxB = 0 would instead tell MATLAB to overwrite whatever is stored in "uxB" with the number zero!

RxB_sol = solve(uxB==0, RxB);

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

16

Page 17: Notes on MATLAB

syms N1 N2 p_0 x xp L ea1 ea2 Ra ux E A;solve( (L*(3*Ra - L*p_0))/(9*A*E) + (2*L*(9*Ra - 2*L*p_0))/(27*A*E), Ra )

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

Page 18: Notes on MATLAB

Differential Equations in Matlab

18

For first-order ODE, function column vector has only one entry: the expression for dx/dt

Page 19: Notes on MATLAB

19

Page 20: Notes on MATLAB

Example

20

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.

Page 21: Notes on MATLAB

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

x(1) = xx(2) = dx/dtx(3) = yx(4) = 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

Page 22: Notes on MATLAB

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

Page 23: Notes on MATLAB

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

Page 24: Notes on MATLAB

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

Page 25: Notes on MATLAB

APPENDIX

25

Page 26: Notes on MATLAB

26