You are on page 1of 9

Quick Matlab Tutorial

ME 850Z
Instructor: Dr. Gisuk Hwang

Outline
1. Data handling
2. Plot
3. Basic pre-defined functions
4. Recursive statement
5. Conditional statement
6. file input/output

1. Data handling
If you have question on this, please type help followed by the function name.
If you want to check there is a function that is available in matlab, type lookfor followed by the key words.
>> x =1
x=
1
>> x=0:1
x=
0 1
>> x=0:0.1:1
x=
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000
>> x(3)
ans =
0.2000
>> A = [0 1;1 2]
A=
0 1
1 2
>> A(1,1)
ans =
0
>> A(1,2)
ans =
1
>> B=ones(2,2)
B=
1 1
1 1
>> C=zeros(2,2)
C=
0 0
0 0
>> A+B
ans =
1 2
2 3
>> A*B
ans =
1 1
3 3
>> inv(A)

ans =
-2 1
1 0
>> inv(A)*B
ans =
-1 -1
1 1
>> x = -pi/2:0.5:pi/2
y = sin(x)
x=
-1.5708 -1.0708 -0.5708 -0.0708
y=
-1.0000 -0.8776 -0.5403 -0.0707
>> x = -pi/2:0.5:pi/2
for i = 1:5
y(i) = sin(x(i));
end
y
x=
-1.5708 -1.0708 -0.5708 -0.0708
y=
-1.0000 -0.8776 -0.5403 -0.0707

0.4292

0.9292

1.4292

0.4161

0.8011

0.9900

0.4292

0.9292

1.4292

0.4161

>> x = 10;
>> x^2
ans =
100
linspace
Generate linearly spaced vectors
Syntax
y = linspace(a,b)
y = linspace(a,b,n)
Description
The linspace function generates linearly spaced vectors. It is similar to the colon operator ":", but gives direct
control over the number of points.
y = linspace(a,b) generates a row vector y of 100 points linearly spaced between and including a and b.
y = linspace(a,b,n) generates a row vector y of n points linearly spaced between and including a and b. For n < 2,
linspace returns b.
_______________________________________________________
Example
Create a vector of 100 linearly spaced numbers from 1 to 500:
A = linspace(1,500);
Create a vector of 10 linearly spaced numbers from 1 to 36:
A = linspace(1,36,10);
_______________________________________________________
Interpolation
interp1: 1-D data interpolation (table lookup)
Syntax
yi = interp1(x,Y,xi)
____________________________________________________________

function matlab_interp1
clear all
close all
X = 0:10; V = sin(X); Xq = 0:.25:10;
Vq = interp1(X,V,Xq); plot(X,V,'o',Xq,Vq,'rx')
end
___________________________________________________

2. Plot
Syntax
plot(Y)
plot(X1,Y1,...,Xn,Yn)
plot(X1,Y1,LineSpec,...,Xn,Yn,LineSpec)
plot(...,'PropertyName',PropertyValue,...)
plot(axes_handle,...)
h = plot(...)
Example 1: plot a sine curve.
x = -pi:.1:pi;
y = sin(x);
plot(x,y)

Various line types, plot symbols and colors may be obtained with
plot(X,Y,S) where S is a character string made from one element from any or all the following 3 columns:
b blue
. point
- solid
g green
o circle
: dotted
r red
x x-mark
-. dashdot
c cyan
+ plus
-- dashed
m magenta
* star
(none) no line
y yellow
s square
k black
d diamond
w white
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
Example 2: change line property;
x = -pi:.1:pi;

y = sin(x);
plot(x,y,'ro-')
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-4

-3

-2

-1

Example 3: add the title, x and y label


x = -pi:.1:pi;
y = sin(x);
plot(x,y)
title('Sine Function');
xlabel('Radians');
ylabel('Function Value');
Example 4: Add a plot title, axis labels, and annotations.
x = -pi:.1:pi;
y = sin(x);
p = plot(x,y)
xlabel('-\pi \leq \Theta \leq \pi')
ylabel('sin(\Theta)')
title('Plot of sin(\Theta)')
% \Theta appears as a Greek symbol (see String)
% Annotate the point (-pi/4, sin(-pi/4))
text(-pi/4,sin(-pi/4),'\leftarrow sin(-\pi\div4)', 'HorizontalAlignment','left')
% Change the line color to red and
% set the line width to 2 points
set(p,'Color','red','LineWidth',2)

Example 5: Plot multiple line plots on the same axes.


x = -pi:.1:pi;

plot(x,sin(x));
% hold axes and all lineseries properties, such as
% ColorOrder and LineStyleOrder, for the next plot
hold all
plot(x,sin(x+(pi/4)));
Example 6:
Plot multiple line plots on the same axes.
x = -pi:.1:pi;
y1 = sin(x);
y2 = sin(x+pi/2);
plot(x,y1,'ro-',x,y2,'gx--');

1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6

Example 7:
Plot atom structures using atomsplot(pos, R, T)
function. atomsplot function will be available in
Blackboard.

-0.8
-1
-4

-3

-2

-1

Please visualize three types of atoms located at x1 = [1 1 1], x2 = [2 2 2], x3 = [3 3 3], with the radius of 0.1.
___________________________________________
>> pos
pos =
1 1 1
2 2 2
3 3 3
>> R = 0.1
R=
0.1000
>> T
T=
1 2 3
>> atomsplot(pos,R,T)
___________________________________________

3. Basic pre-defined function


a) abs()
>> abs(-10)
ans =
10
b) length()
>> x = 1:3
x=
1 2 3
>> length(x)
ans =
3
c) rand(n,m)
>> rand(1,3)
ans =
0.8147 0.9058 0.1270
d) max()
>> max(1:3)
ans =
3
e) min()
>> min(1:3)
ans =
1
f) clear all -> clear all the variables
g) close all -> close all the figures
h) dot()
>>A = [4 -1 2];
>>B = [2 -2 -1];
Calculate the dot product of A and B.
>>C = dot(A,B)
>>C =
8

4. Recursive Statement: for loop


______________________________
Syntax
for index = values
program statements
end
______________________________
Example 1:
Compute the following equation using for loop.

Sn k
k 1

(a) for n = 10, Sn = 55


(b) for n = 100, Sn = 5050;
___________________
S_n = 0;
n = 100; % maximum index of S_n;, for (b), n = 100;
for i = 1:n % i is the index
S_n = S_n + i;
end
_____________________

5. Conditional Statement: if statement


Syntax
_____________________
if expression
statements
elseif expression
statements
else
statements
end
_____________________
Example 1:
Generate 10 x 10 matrix of MyData having 2 for diagonal and 1 for the abs(i j) = 1 where i, j are matrix indices
for row and column.
______________________
>> % Preallocate a matrix
nrows = 10;
ncols = 10;
myData = ones(nrows, ncols);
% Loop through the matrix
for r = 1:nrows
for c = 1:ncols
if r == c
myData(r,c) = 2;
elseif abs(r - c) == 1
myData(r,c) = -1;
else
myData(r,c) = 0;
end
end
end
____________________________
>> myData
myData =
2 -1 0 0 0
-1 2 -1 0 0
0 -1 2 -1 0
0 0 -1 2 -1

0
0
0
0

0
0
0
0

0
0
0
0

0
0
0
0

0
0
0
0

0
0
0
0
0
0

0
0
0
0
0
0

0
0
0
0
0
0

-1 2 -1 0 0 0 0
0 -1 2 -1 0 0 0
0 0 -1 2 -1 0 0
0 0 0 -1 2 -1 0
0 0 0 0 -1 2 -1
0 0 0 0 0 -1 2

6. File input / output


fprintf: write data to text file
Syntax
fprintf(fileID, formatSpec, A1, , An)
frpintf(formatSpect,A1,,An)

Example
______________________________
Create a sample text file that contains floating-point numbers.
x = 100*rand(8,1);
fileID = fopen('nums1.txt','w');
fprintf(fileID,'%4.4f\n',x);
fclose(fileID);
View the contents of the file.
open nums1.txt
81.4724
90.5792
12.6987
91.3376
63.2359
9.7540
27.8498
54.6882
_______________________________________
fscanf: read data from text file
Syntax
A = fscanf(fileID,formatSpec)example
A = fscanf(fileID,formatSpec,sizeA)
fileID = fopen('nums1.txt','r'); % Open the file for reading, and obtain the file identifier, fileID.
formatSpec = '%f'; %Define the format of the data to read. Use the string, '%f', to specify floating-point numbers.
A = fscanf(fileID,formatSpec) % Read the file data, filling output array, A, in column order. fscanf reapplies the
format, formatSpec, throughout the file.
A=
81.4724
90.5792
12.6987
91.3376
63.2359
9.7540

27.8498
54.6882
%A is a column vector containing data from the file.
fclose(fileID); %Close the file.
formatting string
fprintf('The price of %s on %d/%d/%d was $%.2f.', 'bread', 7, 1, 2006, 2.49)
ans =
The price of bread on 7/1/2006 was $2.49.

References
http://www.mathworks.com/help/symbolic/mupad_ref/ode-solve.html
http://www.math.tamu.edu/REU/comp/matode.pdf
http://www.cs.cmu.edu/~tom/10601_fall2012/recitations/matlab_quickref.pdf

You might also like