0% found this document useful (0 votes)
67 views41 pages

Matlab Basic Programming

This document provides an overview of basic MATLAB commands and functions for programming in MATLAB. It discusses getting help, the workspace, basic commands, arrays and matrices, logical conditions, loops, and conditional statements. Key functions and operations for vectors, matrices, solving equations and more are described in 3 sentences or less.

Uploaded by

Siva Kumar Ch
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views41 pages

Matlab Basic Programming

This document provides an overview of basic MATLAB commands and functions for programming in MATLAB. It discusses getting help, the workspace, basic commands, arrays and matrices, logical conditions, loops, and conditional statements. Key functions and operations for vectors, matrices, solving equations and more are described in 3 sentences or less.

Uploaded by

Siva Kumar Ch
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

U

,O
MATLAB Basic

ED
Programming

,E
AR
M
KU CH. SIVA KUMAR

ASSISTANT PROFESSOR

DEPARTMENT OF ELECTRICAL ENGINEERING

UNIVERSITY COLLEGE OF ENGINEERING


A

OSMANIA UNIVERSITY
IV

HYDERABAD
.S
H
C
Matlab Basics

U
,O
u To start Matlab: Select MATLAB on the menu (if

ED
using Windows). Type “matlab” on the
command line (if using Linux).

,E
AR
M
KU
A
IV
.S
H
C
Getting Help and

U
,O
Looking Up Functions

ED
u To get help on a function type “help function_name”,
e.g., “help plot”.

,E
u To find a topic, type “lookfor topic”, e.g., “lookfor

AR
matrix”

M
KU
A
IV
.S
H
C
U
,O
Matlab’s Workspace

ED
,E
u who, whos – current workspace vars.

AR
u save – save workspace vars to *.mat file.
u load – load variables from *.mat file.

M
u clear all – clear workspace vars.
close all – close all figures
u
KU
u clc – clear screen
u clf – clear figure
A
IV
.S
H
C
U
,O
Basic Commands

ED
,E
u % used to denote a comment

AR
u ; suppresses display of value (when placed at end of
a statement)
... continues the statement on next line

M
u

u eps machine epsilon


KU
u inf infinity
u NaN not-a number, e.g., 0/0.
A
IV
.S
H
C
U
,O
Numbers

ED
,E
u To change format of numbers:

AR
format long, format short, etc.
See “help format”.

M
u Mathematical functions: sqrt(x), exp(x), cos(x), sin(x),
sum(x), etc.
KU
u Operations: +, -, *, /
u Constants: pi, exp(1), etc.
A
IV
.S
H
C
U
,O
Arrays and Matrices

ED
,E
u v = [-2 3 0 4.5 -1.5]; % length 5 row
vector.

AR
u v = v’; % transposes v.
v(1); % first element of v.

M
u

u v(2:4); % entries 2-4 of v.


KU
u v([3,5]); % returns entries 3 & 5.
u v=[4:-1:2]; % same as v=[4 3 2];
A

u a=1:3; b=2:3; c=[a b]; à c = [1 2 3 2 3];


IV
.S
H
C
U
,O
Arrays and Matrices (2)

ED
,E
u x = linspace(-pi,pi,10); % creates 10 linearly-spaced
elements from –pi to pi.

AR
u logspace is similar.
A = [1 2 3; 4 5 6]; % creates 2x3 matrix

M
u

u A(1,2) % the element in row 1, column 2.


KU
u A(:,2) % the second column.
u A(2,:) % the second row.
A
IV
.S
H
C
U
,O
Arrays and Matrices (3)

ED
,E
u A+B, A-B, 2*A, A*B % matrix addition, matrix
subtraction, scalar multiplication, matrix multiplication

AR
u A.*B % element-by-element mult.
A’ % transpose of A (complex-

M
u
conjugate transpose)
KU
u det(A) % determinant of A
A
IV
.S
H
C
U
,O
Creating special matrices

ED
,E
u diag(v) % change a vector v to a
diagonal matrix.

AR
u diag(A) % get diagonal of A.
eye(n) % identity matrix of size n.

M
u

u zeros(m,n) % m-by-n zero matrix.


KU
u ones(m,n) % m*n matrix with all ones.
A
IV
.S
H
C
U
,O
Logical Conditions

ED
,E
u ==, <, >, <=, >=, ~= (not equal), ~ (not)

AR
u & (element-wise logical and), | (or)
u find(‘condition’) – Return indices of A’s elements that
satisfies the condition.

M
u Example: A = [7 6 5; 4 3 2];
KU
find (‘A == 3’); --> returns 5.
A
IV
.S
H
C
U
Solving Linear Equations

,O
ED
u A = [1 2 3; 2 5 3; 1 0 8];
u b = [2; 1; 0];

,E
u x = inv(A)*b; % solves Ax=b if A is invertible.

AR
(Note: This is a BAD way to solve the
equations!!! It’s unstable and inefficient.)

M
u x = A\b; % solves Ax = b.
KU
(Note: This way is better, but we’ll learn how to
program methods to solve Ax=b.)
A

Do NOT use either of these commands in your


IV

codes!
.S
H
C
U
,O
More matrix/vector
operations

ED
,E
u length(v) % determine length of vector.

AR
u size(A) % determine size of matrix.
u rank(A) % determine rank of matrix.

M
u norm(A), norm(A,1), norm(A,inf)
% determine 2-norm, 1-norm,
KU
and infinity-norm of A.
• norm(v) % compute vector 2-norm.
A
IV
.S
H
C
U
,O
For loops

ED
,E
u x = 0;

AR
for i=1:2:5 % start at 1, increment by 2
x = x+i; % end with 5.

M
end
KU
This computes x = 0+1+3+5=9.
A
IV
.S
H
C
U
,O
While loops

ED
,E
u x=7;

AR
while (x > = 0)
x = x-2;

M
end;
KU
This computes x = 7-2-2-2-2 = -1.
A
IV
.S
H
C
U
,O
If statements

ED
,E
u if (x == 3)

AR
disp(‘The value of x is 3.’);
elseif (x == 5)

M
disp(‘The value of x is 5.’);
else
KU
disp(‘The value of x is not 3 or 5.’);
end;
A
IV
.S
H
C
U
,O
Switch statement

ED
,E
u switch face
case {1}

AR
disp(‘Rolled a 1’);
case {2}

M
disp(‘Rolled a 2’);
otherwise
KU
disp(‘Rolled a number >= 3’);
end
A

u NOTE: Unlike C, ONLY the SWITCH statement


IV

between the matching case and the next case,


otherwise, or end are executed. (So breaks are
unnecessary.)
.S
H
C
U
,O
Break statements

ED
,E
u break – terminates execution of for and while loops.
For nested loops, it exits the innermost loop only.

AR
M
KU
A
IV
.S
H
C
U
,O
Vectorization

ED
,E
u Because Matlab is an interpreted language, i.e., it is not
compiled before execution, loops run slowly.

AR
u Vectorized code runs faster in Matlab.
Example: x=[1 2 3];

M
u

for i=1:3 Vectorized:


KU
x(i) = x(i)+5; VS. x = x+5;
end;
A
IV
.S
H
C
U
,O
Graphics

ED
,E
u x = linspace(-1,1,10);

AR
u y = sin(x);
u plot(x,y); % plots y vs. x.

M
u plot(x,y,’k-’); KU % plots a black line
of y vs. x.
• hold on; % put several plots in
the same figure window.
A
IV

• figure; % open new figure window.


.S
H
C
U
,O
Graphics (2)

ED
,E
u subplot(m,n,1) % Makes an mxn array

AR
for plots. Will place plot in 1st position.

M
KU
X
A
IV

Here m = 2 and n = 3.
.S
H
C
U
,O
Graphics (3)

ED
,E
u plot3(x,y,z) % plot 2D function.

AR
u mesh(x_ax,y_ax,z_mat) – surface plot.
u contour(z_mat) – contour plot of z.
axis([xmin xmax ymin ymax]) – change axes

M
u

u title(‘My title’); - add title to figure;


KU
u xlabel, ylabel – label axes.
u legend – add key to figure.
A
IV
.S
H
C
U
,O
Examples of Matlab Plots

ED
,E
AR
M
KU
A
IV
.S
H
C
U
,O
Examples of MATLAB Plots

ED
,E
AR
M
KU
A
IV
.S
H
C
U
,O
Examples of MATLAB Plots

ED
,E
AR
M
KU
A
IV
.S
H
C
U
,O
File Input/Output

ED
,E
u fid = fopen(‘in.dat’,’rt’); % open text file for
reading.

AR
u v = fscanf(fid,’%lg’,10); % read 10 doubles
from the text file.

M
u fclose(fid); % close the file.
KU
u help textread; % formatted read.
u help fprintf; % formatted write.
A
IV
.S
H
C
U
,O
Example Data File

ED
,E
Sally Type1 12.34 45 Yes

AR
Joe Type2 23.54 60 No
Bill Type1 34.90 12 No

M
KU
A
IV
.S
H
C
U
,O
Read Entire Dataset

ED
,E
fid = fopen(‘mydata.dat’, ‘r’); % open file

AR
for reading.

% Read-in data from mydata.dat.

M
[names,types,x,y,answer] = textread(fid,’%s%s%f%d%s’);
KU
fclose(fid); % close file.
A
IV
.S
H
C
U
,O
Read Partial Dataset

ED
,E
fid = fopen(‘mydata.dat’, ‘r’); % open file

AR
for reading.

M
% Read-in first column of data from
KU
mydata.dat.
[names] = textread(fid,’%s %*s %*f %*d
%*s’);
A
IV

fclose(fid); % close file.


.S
H
C
U
,O
Read 1 Line of Data

ED
,E
fid = fopen(‘mydata.dat’, ‘r’); % open
file

AR
% for reading.

M
% Read-in one line of data corresponding
% to Joe’s entry.
KU
[name,type,x,y,answer] =…
textread(fid,’%s%s%f%d%s’,1,…
A

’headerlines’,1);
IV

fclose(fid); % close file.


.S
H
C
U
,O
Writing formatted data.

ED
,E
% open file for writing.

AR
fid = fopen(‘out.txt’,’w’);

% Write out Joe’s info to file.

M
fprintf(fid,’%s %s %f %d… %s\n’,name,type,x,y,answer);
KU
fclose(fid); % close the file.
A
IV
.S
H
C
U
,O
Keeping a record

ED
,E
u To keep a record of your session, use the
diary command:

AR
diary filename

M
x=3
KU
diary off
A

This will keep a diary called filename


IV

showing the value of x (your work for this


session).
.S
H
C
U
,O
Timing

ED
,E
u Use tic, toc to determine the running time of an
algorithm as follows:

AR
tic

M
commands… KU
toc

This will give the elapsed time.


A
IV
.S
H
C
U
Scripts and Functions

,O
ED
u Two kinds of M-files:

,E
- Scripts, which do not accept input
arguments or return output arguments.

AR
They operate on data in the workspace.

M
- Functions, which can accept input
KU
arguments and return output
arguments. Internal variables are
local to the function.
A
IV
.S
H
C
U
,O
M-file functions

ED
,E
u function [area,circum] = circle(r)

AR
% [area, circum] = circle(r) returns the
% area and circumference of a circle

M
% with radius r.
area = pi*r^2;
KU
circum = 2*pi*r;
A

• Save function in circle.m.


IV
.S
H
C
U
,O
M-file scripts

ED
,E
u r = 7;

AR
[area,circum] = circle(r);
% call our circle function.
disp([‘The area of a circle having…

M
radius ‘ num2str(r) ‘ is ‘… num2str(area)]);
KU
• Save the file as myscript.m.
A
IV
.S
H
C
U
,O
Interactive Example

ED
,E
u Write a Matlab program to compute the following sum

AR
∑1/i2, for i=1, 2, …, 10
two different ways:

M
1. 1/1+1/4+…+1/100
2. 1/100+1/81+…+1/1.
KU
A
IV
.S
H
C
U
Solution

,O
ED
% Forward summation
forwardsum = 0;

,E
for i=1:10
forwardsum = forwardsum+1/(i^2);

AR
end;

M
% Backward summation
backwardsum = 0;
KU
for i=10:-1:1
backwardsum = backwardsum+1/(i^2);
A

end;
IV
.S
H
C
U
,O
Interactive Example

ED
,E
u Write a Matlab function to multiply two

AR
n-by-n matrices A and B. (Do not use built-in functions.)

M
KU
A
IV
.S
H
C
U
,O
Solution

ED
,E
function [C] = matrix_multiply(A,B,n)

AR
C = zeros(n,n);
for i=1:n Can this code be written so that it

M
for j=1:n runs faster?
for k=1:n
KU
C(i,j) = C(i,j) + A(i,k)*B(k,j);
end;
A

end;
IV

Hint: Use vectorization.


end;
.S
H
C
U
,O
Solution

ED
,E
u Script to use for testing:

AR
n = 10;

M
A = rand(n,n);
B = rand(n,n);
KU
C = matrix_multiply(A,B,n);
A
IV
.S
H
C

You might also like