You are on page 1of 31

MAE 2100 S16 Lecture 4

Topics (Chapter 2.10,11; Lecture Notes )


ReviewLecture 3Questions
Using Vectors & Dimensioning Arrays
Plotting
Built-In Matlab Functions
Programming Approach
Week 4 Lab Assignment (Posted)
Week 4 Quiz Preview
MAE 2100 Lecture 4 1
Review

Lecture 3 Topics (Chapter 2.8-10)


Scalar Operations
Array and Matrix Operations
Lab/Quiz Questions

MAE 2100 Lecture 4 2


e notation and Creating a Time Vector
e notation Creating a Time Vector
>> % 100 mv % Definitions
100e-3 % ti = initial time tf = final time dt = delta time
ans = % Npts = number of points
0.1000 %
>> % 50 ns % Example - ti, Npts, dt are known ... tf is unknown
50e-9 ti=0;
ans = Npts=10;
5.0000e-08 dt=2;
>> % 44 microns
44e-6 t=dt*[1:Npts]; % wrong - does not start at ti = 0
ans = disp(t);
4.4000e-05 2 4 6 8 10 12 14 16 18 20
>> 44*e-6
??? Undefined function or variable 'e'. >> t=dt*([1:Npts]-1);
disp(t);
>> 44*1e-6 0 2 4 6 8 10 12 14 16 18
ans =
4.4000e-05 >> t=(dt*[1:Npts])-dt;
>> 44*10^-6 disp(t);
ans = 0 2 4 6 8 10 12 14 16 18
4.4000e-05
>> t=dt*[0:Npts-1];
disp(t);
0 Lecture
MAE 2100 2 44 6 8 10 12 14 16 18 3
Creating a Time Vector - Using linspace

% Definitions
% ti = initial time tf = final time dt = delta time
% Npts = number of points
%
% Example - ti, Npts, dt are known ... tf is unknown
ti=0;
Npts=10;
dt=2;

>> linspace(0,dt*Npts,Npts) % tfinal is wrong so effective delta time is wrong


ans =
0 2.2222 4.4444 6.6667 8.8889 11.1111 13.3333 15.5556 17.7778 20.0000
>>
>> linspace(0,dt*Npts-1,Npts) % tfinal is still wrong so effective delta time is wrong
ans =
0 2.1111 4.2222 6.3333 8.4444 10.5556 12.6667 14.7778 16.8889 19.0000
>>
>> linspace(0,dt*(Npts-1),Npts) % correct
ans =
0 2 4 6 8 10 12 14 16 18

MAE 2100 Lecture 4 4


Using Vectors for Multiple-Valued Parameters

This issue can be demonstrated using a linear


equation of the form y = ax + b with the x range
from 0 to 10 & b=2. Assume that we want to look
at 4 different slopes: 1, 2, 3, and 4. In Matlab:
Do this: >> a = [1 2 3 4];
Not this: >> a1 = 1; a2 = 2; a3 = 3; a4 = 4;
Generate 4 curves:
>> x = [0:0.01:10];
>> y(1,:) = a(1) * x + b;
>> y(2,:) = a(2) * x + b;
etc row 2, all
columns MAE 2100 Lecture 4 5
Dimensioning (initializing) Arrays

In some programming languages, for example the


traditional scientific language FORTRAN, arrays
must be dimensioned before being used. That is,
the name and required size for the array must be
specified. In Matlab, arrays are dimensioned on
the fly by Matlab, but dimensioning arrays using a
zeros command is still good practice.

For the linear example

MAE 2100 Lecture 4 6


Plotting

Basic plotting
Multiple things on a single set of axes
Axis labels and grid on
Subplots
Line/marker control
Legend

MAE 2100 Lecture 4 7


Figure Window

The figure command opens a new (blank) Figure Window if


a # is not specified, Matlab uses the lowest available number

The figure number can also be specified

MAE 2100 Lecture 4 8


Plotting Vector Values versus Element Numbers

The plot command with a single vector as the argument and


with no line or marker control will plot the specified vector
versus element number (1,2,3) using a solid blue line
Here, y is plotted versus 1,2,3
even though it was calculated
based on x=[2 4 6]

A line is shown
but only the
points (1,4)
(2,16) and
(3,36) exist

MAE 2100 Lecture 4 9


Plotting Vector Values versus Element Numbers

The hold on command allows us to add data to an existing


graph. Adding ro to the plot command tells Matlab to plot
the vector y using red circle markers remember, the blue
line was plotted using the plot(y) command

Now the actual


data points are
shown and
connected with
a line

MAE 2100 Lecture 4 10


Line & Marker Control

help plot shows line type, marker types & colors

MAE 2100 Lecture 4 11


Plotting y versus x with Labels and the Grid

This time, we plot y versus x using black squares: ks In the


plot command, we enter plot(x,y) to make a graph of y versus
x. The grid has also been added using the grid on command
and labels have been added using the commands shown.

MAE 2100 Lecture 4 12


Plotting y versus x Showing the Points and the Line
Now we plot the x,y data showing the
points & the line in the same color (top
figure) and then using different colors
(lower figure) this is done by plotting
the data twice in a single plot command

MAE 2100 Lecture 4 13


Plotting Multiple Curves on the Same Axes

We can plot multiple curves on the same axes by


repeating x,y combinations (using this approach,
line colors are automatically assigned):
>> figure, plot( x,y(1,:), x,y(2,:), x,y(3,:), x,y(4,:) )
opens new
figure or by using the hold on command
>> figure, plot(x,y(1,:)), hold on, plot(x,y(2,:)),
plot(x,y(3,:)), plot(x,y(4,:)), hold off

use hold off to make sure you dont keep


plotting stuff on the same set of axes

MAE 2100 Lecture 4 14


Multiple Curves on the Same Axes Linear Example

MAE 2100 Lecture 4 15


Subplots

The subplot command creates multiple xy


plots on the same figure

MAE 2100 Lecture 4 16


Subplots Linear Example

The 4 lines can be plotted on 4 separate axes


on one figure

title and axis labels


must be specified for
each subplot
MAE 2100 Lecture 4 17
Legends

The strings are assigned to data based on the


order of appearance; that is, string1 goes with
the first set of xy data plotted, and so on
You can drag the Legend to an open space on the
graphlater, we will automatically position the
Legend in 2100 Lecture 4position
MAEbest 18
Line & Marker Control and Legends Linear Example

Lets redo the linear example with x = [0 2 4 6]

MAE 2100 Lecture 4 19


Line & Marker Control and Legends Linear Example

MAE 2100 Lecture 4 20


The max (and min) Commands

Cautionwatch the direction max is looking across


MAE 2100 Lecture 4 21
The max (and min) Commands

The default or [],1)


yields a row vector

The max value


and its position in
the vector can
be assigned to
variables
[],2) yields a
column vector
Evaluation of the original vector
Applying max at the element number of the
twice yields the max value gives you the max value
overall max value
MAE 2100 Lecture 4 22
The max Command
Generate two sin2x and find
there max value and position

The sin2x curves are plotted vs


element number, not vs x
MAE 2100 Lecture 4 23
More on the max Command

80 158
Think in terms of plotting y vs x. When we do max(y), we get
the max value of y (val) and the element number (pos) of the
max value in the array y. If we want the x value corresponding
to the max value of y, then we will want to evaluate x at the
element number for the max(y):
MAE 2100 Lecture 4 x(pos(1)) or x(pos(2))24
More on the max Command another example

t=[0:.6:2*pi];
y=sin(t);
figure,subplot(2,1,1),plot(t,y,'ro','MarkerSize
',8,'MarkerFaceColor','r'),grid on
xlabel('t'),ylabel('y')
subplot(2,1,2),plot(y,'ro','MarkerSize',8,'Mar
kerFaceColor','r'),grid on
xlabel('Element Number'),ylabel('y')

[mv,mp]=max(y)
subplot(2,1,2),hold
on,plot(mp,mv,'bs','MarkerSize',16,'LineWid
th',3)
subplot(2,1,1),hold
on,plot(t(mp),mv,'bs','MarkerSize',16,'Line
Width',3)
mv =
0.9738
mp =
4 MAE 2100 Lecture 4 25
More on the max Command abs and segments

ylen=length(y)
ymidpt=round(ylen/2)
[amv1,amp1]=max(abs(y(1:ymidpt)))
[amv2,amp2]=max(abs(y(ymidpt:end)))

subplot(2,1,2),hold on,
plot([amp1 amp2+ymidpt-1],[amv1 amv2],
'bs','MarkerSize',16,'LineWidth',3)
subplot(2,1,1),hold on,
plot([t(amp1) t(amp2+ymidpt-1)],[amv1 amv2],
'bs','MarkerSize',16,'LineWidth',3)

ylen = 11
ymidpt = 6
amv1 = 0.9738
amp1 = 4
amv2 = 0.9962
amp2 = 4

MAE 2100 Lecture 4 26


polyfit and polyval Commands
>> help polyfit
POLYFIT Fit polynomial to data.
P = POLYFIT(X,Y,N) finds the coefficients of a polynomial P(X) of
degree N that fits the data Y best in a least-squares sense. P is a
row vector of length N+1 containing the polynomial coefficients in
descending powers, P(1)*X^N + P(2)*X^(N-1) +...+ P(N)*X + P(N+1).

Note: polyfit determines the best fit by minimizing


the sum of the squared errors between the data and the
fit line this is covered in detail in MAE 3100
>> help polyval
POLYVAL Evaluate polynomial.
Y = POLYVAL(P,X) returns the value of a polynomial P evaluated at X. P
is a vector of length N+1 whose elements are the coefficients of the
polynomial in descending powers.

Y = P(1)*X^N + P(2)*X^(N-1) + ... + P(N)*X + P(N+1)

If X is a matrix or vector, the polynomial is evaluated at all


points in X. See POLYVALM MAEfor
2100 Lecture 4 in a matrix sense.
evaluation 27
The polyfit and polyval Old Linear Example

MAE 2100 Lecture 4 28


The polyfit and polyval dense x example
% create the initial data and plot
x=[1 2 4 5];
y=x.^3;
figure,plot(x,y,'ro','MarkerSize',15,'LineWidth',2)
% polyfit and polyval at original points - plot
xycoef=polyfit(x,y,3);
xyfit=polyval(xycoef,x);
hold on,plot(x,xyfit,'b+','MarkerSize',20,'LineWidth',2)
plot(x,xyfit,'k','LineWidth',2)
% polyval at a more dense x
xdens=linspace(min(x),max(x),10*length(x));
xyfit_dens=polyval(xycoef,xdens);
plot(xdens,xyfit_dens,'g.','MarkerSize',8)

MAE 2100 Lecture 4 29


Programming Approach

Outline your code


Use the outline to create comment statements
Write and then test each little piece of code
Use plots as a diagnostic tool for each piece
Test pieces of code from the command line
Test pieces of code using test.m files

MAE 2100 Lecture 4 30


Week 4 Quiz Preview

%% 1. Create 3x3 matrix,

%% 2. Multiply arrays on an element by element basis

%% 3. Do matrix multiplication

%% 4. Do scalar multiplication of a subarray

%% 5. Make a column vector

%% 6. Multiply column vector by a subarray on an element by element basis

%% 7. Correct code involving element by element operations

MAE 2100 Lecture 4 31

You might also like