Overview of Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

ME 350 Programming & Numerical Methods

Overview of Programming, Intro to MATLAB


The art of programming involves Getting the right values in the right variables at the right
time Brian Hahn.
Interactive Computing with MATLAB
To launch MATLAB click on the Start icon then click on Programs, select and click on
MATLAB icon then MATLAB R201b 32 bit or MATLAB R2010b 64bit. This should launch the
default multi-window user interface associated with MATLAB shown Figure 2.1 p. 10

Command Window (Your main interaction point with MATLAB)


Command History (Tracks commands entered in the command window)
Current directory (Folder); detail. Highlight browser button
Workspace

>> is the MATLAB prompt


To quit MATLAB
>>quit or
>>exit
>>path
yields many path pointers to the location of files, programs and applications including:
The My Documents\MATLAB folder. This is the default folder in which you can save your
MATLAB session files.
***Other important files and programs that will be used extensively in ME 350 reside in the
nmm folder on the network drive P for example:
P:\Programs\Matlab8x64\toolbox\nmm
P:\Programs\Matlab8x64\toolbox\nmm\data***
etc.
Note useful links and navigation tools on the MATLAB Command Window
1|Page

Definition of variables
Variables in MATLAB can be defined with significant flexibility with the programmer (you) in
charge
Variable length maximum recognizable number of characters is 31 or 63 (for a 32-bit and 64-bit
system respectively) and it can be a combination of
a-z; A-Z; 0-9; and the _ the underscore. Other special symbols like @#$% are NOT acceptable
Case sensitive; e.g. aA
First character for a variable must be a letter
Individual variables are stored as such (scalars or real numbers)
A matrix is an m*n (rows, columns) definition and storage of a set of numbers.
A vector (array) is special matrix with one row or one column.
Basic computations with MATLAB

MATLAB can be used as an expression evaluator

>> 2+6-4
ans =
4
>> ans/2
ans =
2
>> ans/3
ans =
0.6667

2|Page

>> help ans


ANS is the most recent answer.
ANS is the variable created automatically when expressions are not assigned to anything else.
It is a short form for ANSwer. This variable gets overwritten with each usage.

Order of precedence in computations


Remember PEMDAS?
Refer to p. 22
>>8+3*5
ans=
23
will be evaluated by MATLAB by using the precedence sequence which effectively by first
computing 3*5 storing it in memory then adding 8, the arithmetic equivalent of 8+(3*5)
Would you expect the following 2 computations to yield the same answer?
>>27^(1/3) + 32^0.2
>>27^1/3+32^0.2

Computations involving trigonometric functions:


The default reference basis is that angles are submitted to MATLAB in radians. Use the
conversion radians = 180o as the need arises.
Use the conversion factor, radians is equivalent to 180o in real time when dealing with
angles in degrees, e.g. compute the sine of 30 degrees:
>> sin(30/180*pi)
ans =
0.5000
Alternatively use the degrees-based built-in trigonometric function sind:
3|Page

>> sind(30)
ans =
0.5000
Similarly for other trigonometric functions, cosd, tand etc.

Built-in variable and functions.


MATLAB has a number of common Mathematical functions and parameters pre-defined and
ready for use at the command line or via script files or functions. We will explore several of
these throughout ME 350. Alternatively you can get on-line documented MATLAB help as
follows:
>>help functionName
>>doc functionName
For example:
>>help log
>>doc plot
Differentiate between logarithmic scales (e.g. natural log ln and common log log10)
>>log(x)

%natural log of x, i.e. ln(x)

log(3.2) = 1.1632
>>log10(x)

%common log of x; i.e log(x)

log10(3.2) = 0.5051
Differentiate between the inverse of logarithmic scales
>>exp(x)

%inverse of the natural log; i.e. ex

exp(1.1632) = 3.200
>>10x

%inverse of the common log i.e 10x

10^(0.5051) = 3.1996
4|Page

Arrays and matrices


>>x=[1 3 0 -1 5]

[Ret]

Results in a row vector with entries 1, 3, 0, -1, 5


Adding a semicolon at the end of suppresses the output but retains the vector in memory

>>x=[1 3 0 -1 5];

[Ret]

would result in no output in the command window because the semicolon suppresses the
output. One of the ways to see the numerical value of the variable x is to issue a specific display
command like
>>disp(x) [Ret]
or simply type:
>>x

[Ret]

To display x as a column array, use the transpose operator (the apostrophe), or semicolons to
separate entries of the array
>>x=[1 3 0 -1 5]
or
>>x=[1;3;0;-1;5]

Suppose you enter the following commands at the MATLAB prompt:


>>a=[4 5 6];
>>b=[7 8];
What would you get by entering the following?
>>c=[a -b]
Try this without MATLAB first, then confirm with MATLAB
NOTE values of vectors a and b are separated by a blank space. The (safer) option is to use a
coma instead of a blank space to avoid accidental typing blunders, for instance:
5|Page

What would you if you forgot the space between a and b as follows:
>>c=[a-b]

Manual entry of matrices can be accomplished separating column entries by spaces and row entries by
semicolons for example:

>> A=[1 2 3;4 5 6;7 8 9] %would result in the 3X3 matrix echoed below
A=
1

Matrices can also be created using built-in functions e.g. eye, diag, ones, linspace, etc.
We will explore these throughout the class.
Say you want to define a 3X4 matrix with ones in it,
>>nr=3

%nr=number of rows

>>nc =4

%nc=number of columns

>>mymat=ones(nr,nc)

%generates a 3X4 matrix called mymat, with 1 entries

mymat =
1

6|Page

Use of the eye function to create identity matrix of rank 5


>> C=eye(5)
C=
1

Familiarize ways of manipulating matrices including a review of mathematical operations with


matrices. Explore tricks to use the eye command but end up with non-unity entries in the main
diagonal. What if mn?

Use of the colon operator to define/manipulate vectors


>>x=1:15

start at 1, default incrementation is 1, end at 15

>>x=1:0.5:15 start at 1, increment by 0.5, terminate at 15


>>x=15:-0.2:0 start at 15, decrement by 0.2, terminate at 0

The linspace operator


Offers flexibility to the automatic determination of incrementation especially when dealing
with non-integer functions or ranges e.g.
>>x=linspace(0,pi)

% generate 100 equally spaced points between 0 and

>>x=linspace(0,pi,46)

%generate 46 equally spaced points between 0 and

Determine the linspace equivalence of an array from the following


>>x=0:pi/25:3*pi % i.e. an array between 0 and 3, in steps of pi/25
This will result in 76 equidistant points or stations (25*3+1) to account for the zero

7|Page

>>x=linspace(0,3*pi,76)

%generate 76 equally spaced real numbers from 0 to 3

The logspace operator


The logspace operator generates logarithmically spaced points between the decades of the
limits
>>x=logspace(x1, x2) %Generates 50 logarithmically spaced points between the limits 10x1 and
10x2.
>>x=logspace(x1,x2,n) %Generates n logarithmically spaced points between the limits 10x1 and
10x2.
For more see
>>help logspace

Array operations
When faced with a series of computations that could be accomplished using loops, coding
errors or blunders are possible. Even if one is successful in debugging the code completely,
accomplishing the computations is quite sluggish.

Consider the case where you need to compute the cosine of 5 equally spaced values of x as
follows:
cos(x) for 0 x
By observation you notice that you will need 5 locations along x starting at 0 ending at ,
resulting in the distance between stations of 0.25
In MATLAB once you define the range of values of x they are interpreted and saved as a vector,
in the next command MATLAB computes the 5 values of cos(x) at once as an array operation.
>> x=0:pi/4:pi
x=
0 0.7854 1.5708 2.3562 3.1416
8|Page

>> y=cos(x)
y=
1.0000 0.7071 0.0000 -0.7071 -1.0000

Element by element operations are accomplished with the aid of .*, ./ and .^ for array
multiplication, division and exponentiation respectively.
>> x=[1 2 3]; y=[4 5 6];
>> w=x.*y
w=
4 10 18
>> v=x./y
v=
0.2500 0.4000 0.5000

Can array operations be applied to matrices?


Yes, as long as matrix dimensions are equal
>> P=[1 2 3;4 5 6;7 8 9];
>> Q=[9 7 8;6 5 4;3 2 1];
>> R=P.*Q

R=
9 14 24
24 25 24
21 16

9|Page

Please note that P.*Q is NOT the same as P*Q

Array exponentiation is accomplished as:


>> P.^(1/2)

%Compute the square roots of members of the array

ans =
1.0000 1.4142 1.7321
2.0000 2.2361 2.4495
2.6458 2.8284 3.0000
>> Q.^2

%Compute the squares of members of the array

ans =
81 64 49
36 25 16
9

When matrix or array dimensions are not equal MATLAB responds with an error message
>> Q1=[9 8 7;6 5 4];
>> R1=P.*Q1
??? Error using ==> times
Matrix dimensions must agree.

10 | P a g e

Plotting with MATLAB


For any ordered pair of x,y entries, the default plot representation in MATLAB will be with
piecewise linear segments

>> x=[-2 0 1 3 4 7 10 13];


>> y=[3 -2 5 9 6 3 4 0];
>>plot(x,y)

11 | P a g e

>>plot(x,y,'*')

>> help plot


Will echo online documentation related to the plotting syntax in MATLAB. The choices of color,
symbol and line types are summarized in table 2.6 p. 64 in the text

Adding functionality to plotting,

Example from Hahn


Generate a plot of e-0.2xsin(x) over the domain 0 to 6 in intervals of /20
Main points

Specify the range of x using array syntax


Proper syntax for expressing e-0.2x
Array multiplication of the two functions
Plotting with annotation
12 | P a g e

Saving a pdf version of the plot


Embedding a pdf plot into a Word document

Create a MATLAB script file and name it hahneg.m


Enter the following commands into hahneg.m, run the script file
x=0:pi/20:6*pi;
y=exp(-0.2*x).*sin(x);
plot(x,y,'b')
grid on
xlabel('x'),ylabel('y')
title('Example plot with annotations from Hahn')
Insert hahneg.jpg

More examples involving plot commands in Chapter 5

13 | P a g e

Alternative scaling
Ref. Appendix B, from p. 636
Experiment with the linspace command and different plotting commands which effectively
scales the axes

x=linspace(0,3);
y=10*exp(-2*x);
plot(x,y) %use semilogy, semilogx, loglog in the place of plot for plotting options
grid on

Plot of x y

14 | P a g e

Semilogy plot. Note y axis has been rescaled to the log scale
Try plotting with semilogx and loglog

Multiple plots
Ref. Chapter 5
Syntax for subplots
subplot(nrows,ncols,thisplot)
plot(this plot); include all plotting annotations
Create a script file with commands shown on p. 69 Recktenwald
x is defined once
x = linspace(0,2*pi);
subplot(2,2,1);
plot(x,sin(x)); axis([0 2*pi -1.5 1.5]); title('sin(x)');
15 | P a g e

subplot(2,2,2);
plot(x,sin(2*x)); axis([0 2*pi -1.5 1.5]); title('sin(2x)');
subplot(2,2,3);
plot(x,sin(3*x)); axis([0 2*pi -1.5 1.5]); title('sin(3x)');
subplot(2,2,4);
plot(x,sin(4*x)); axis([0 2*pi -1.5 1.5]); title('sin(4x)');
Insert multiple plots

16 | P a g e

You might also like