Programming in MATLAB
Download
Report
Transcript Programming in MATLAB
Programming in MATLAB
ELEC 206
Computer Applications for
Electrical Engineers
Dr. Ron Hayne
Problems with Two Variables
Two Scalars
x
y
A
A
=
=
=
=
Two Vectors
3;
5;
x * y
15
Scalar and Vector
x
y
A
A
=
=
=
=
x = 1:5;
y = 1:0.5:3;
A = x * y
Error
Two Vectors (by element)
1:5;
5;
x * y
5 10 15 20 25
206_M5
x
y
A
A
=
=
=
=
1:5;
1:0.5:3;
x .* y
1 3 6 10 15
2
Problems with Two Variables
Results of element-by-element calculations
x
1
1.0
1.5
y
2.0
2
3
5
1
3
6
2.5
3.0
4
10
?
15
All combinations of x and y
[X Y] = meshgrid(x,y)
A = X .* Y
206_M5
3
Example
Plot voltage vs time for various RC time constants
v
e t /
V0
Voltage vs Time for Various Time Constants
1
tau=0.5
tau=1.0
tau=2.0
0.9
0.8
0.7
Voltage
0.6
0.5
0.4
0.3
0.2
0.1
0
0
0.5
1
1.5
206_M5
2
2.5
Time
3
3.5
4
4.5
5
4
Example
v
e t /
V0
time = 0:0.1:5;
tau = [0.5 1.0 2.0];
[TIME TAU] = meshgrid(time,tau);
V = exp(-TIME./TAU);
plot(time,V)
206_M5
5
Input / Output
User Defined Input
Prompt user for input
var = input('Prompt string')
Output Options
Display Function
disp(var)
disp('Output string')
Number to String Function
num2str(var)
206_M5
6
Input / Output
Formatted Output
fprintf('format string', var, ...)
%f
%e
%w.pf
\n
\t
fixed point
exponential notation
w=width, p=precision
linefeed (endl)
tab
Example
fprintf('The answer is %5.2f volts.\n', v)
The answer is
5.25 volts.
206_M5
7
Input / Output
Formatted Output
Example
patient = 1:3;
temp = [98.6, 100.1, 99.2];
hist = [patient;temp];
2.0
3.0
1.0
98.6 100.1 99.2
fprintf('Patient %3.0f temp of %6.1f\n',hist)
Patient
Patient
Patient
1 temp of
2 temp of
3 temp of
206_M5
98.6
100.1
99.2
8
Example Revisited
% RC Time Constant Example with User Input
clear, clc
% Request input from user
v0 = input('Input initial voltage: ');
tau = input('Input 3 time constants as a vector: ');
last = input('Input max time: ');
incr = input('Input time increment: ');
time = 0:incr:last;
[TIME TAU] = meshgrid(time,tau);
V = v0*exp(-TIME./TAU);
plot(time,V)
legend(num2str(tau(1)),num2str(tau(2)),...
num2str(tau(3)))
206_M5
9
Functions
Functions written as M-files
function s=add3(x)
% Function that adds 3 to array x
s=x+3;
File name must be same as function name
add3.m
Comments used by help function
help add3
Used like built-in MATLAB functions
x=[1 2 3];
add3(x)
206_M5
10
Functions
Functions with multiple outputs
function [dist vel accel]=motion(t)
% Function to calculate distance, velocity and
acceleration
accel = 0.5 * t;
vel = accel .* t;
dist = vel .* t;
Local variables not visible outside function
function s=add3(x)
% Function that adds 3 to array x
a=x+3;
s=a;
206_M5
11
Example
Degrees / Radians Conversion Functions
Problem Statement
Create and test two functions:
DR to change from degrees to radians
RD to change from radians to degrees
Input/Output Description
Vector of degree values
Table of degrees to radians
Vector of radian values
Table of radians to degrees
206_M5
12
Example
Hand Example
Degrees Radians
degrees = radians * 180/pi
radians = degrees * pi/180
Algorithm Development
Define vector of degree values
Call DR function to find radians
Output results in a table
Define vector of radian values
Call RD function to find degrees
Output results in a table
206_M5
0
30
60
90
0
0.524
1.047
1.571
13
MATLAB Solution
Functions
function output=DR(x)
%This function changes degrees to radians
output=x*pi/180;
function output=RD(x)
%This function changes radians to degrees
output=x*180/pi;
206_M5
14
MATLAB Solution
%Example 5.4
clear, clc
%Define a vector of degree values
degrees = 0:15:180;
% Call the DR function, and use it to find radians
radians = DR(degrees);
%Create a table to use in the output
degrees_radians =[degrees;radians];
%Generate an output table
disp('A table of degrees to radians')
disp('degrees
radians')
fprintf('%6.0f
%8.3f\n',degrees_radians)
%Put a blank line in output to separate tables
disp(' ')
206_M5
15
MATLAB Solution
%Define a vector of radian values
radians = 0:pi/12:pi;
%Call the RD function, and use it to find degrees
degrees = RD(radians);
%Generate an output table
disp('A table of radians to degrees')
disp('radians
degrees')
fprintf('%9.3f
%10.3f \n',[radians;degrees])
206_M5
16
Control Structures
Sequence
Sequence of steps performed one after another
Selection
Condition evaluated as true or false
if true, one set of statements executed
if false, another set of statements executed
Repetition
Repeat (loop through) a set of steps
As long as a condition is true
206_M5
17
Conditional Expressions
Relational Operators
<
<=
>
>=
==
~=
Logical Operators
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal
&
|
~
and
or
not
True and False
1
0
True
False
206_M5
18
Selection Structures
find Command
Often used instead of both if and loop structures
Returns vector of indices of nonzero elements of vector
Example
temp = [100 98 94 101 92];
faulty = find(temp<95);
failtable = [faulty' temp(faulty)']
Example with 2D Matrix...
206_M5
19
Selection Structures
if Statement
if/elseif/else Statement
if condition
statements
end
if condition
statements
elseif condition
statements
else
statements
end
if/else Statement
if condition
statements
else
statements
end
206_M5
20
Example
Assign Letter Grades Scalar Function
function g = grade(x)
%This function requires a scalar input
if(x>=90)
g = 'A';
elseif(x>=80)
g = 'B';
elseif(x>=70)
g = 'C';
elseif(x>=60)
g = 'D';
else
g = 'F';
end
206_M5
21
Example Revisited
Assign Letter Grades Vector Function
function g = gradev(x)
% This function works with vector input
A = find(x>=90);
B = find(x>=80 & x<90);
C = find(x>=70 & x<80);
D = find(x>=60 & x<70);
F = find(x<60);
g(A) = 'A';
g(B) = 'B';
g(C) = 'C';
g(D) = 'D';
g(F) = 'F';
206_M5
22
Loops
Usually not necessary in MATLAB
Avoid the temptation
Much slower
Use matrix calculations and find instead
For Loops
for index=expression
statements
end
While Loops
while condition
statements
end
206_M5
23
Loop Example
For Loop
A=ones(200);
for k=1:length(A(:))
B(k)=A(k)*pi;
end
Matrix Operation
A=ones(200);
B=A*pi;
206_M5
24
Summary
Problems with Two Variables
Input / Output
Functions
Control Structures
206_M5
25