260 likes | 711 Views
Programming in MATLAB. ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne. Two Scalars x = 3; y = 5; A = x * y A = 15 Scalar and Vector x = 1:5; y = 5; A = x * y A = 5 10 15 20 25. Two Vectors x = 1:5; y = 1:0.5:3; A = x * y Error Two Vectors (by element)
E N D
Programming in MATLAB ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne
Two Scalars x = 3; y = 5; A = x * y A = 15 Scalar and Vector x = 1:5; y = 5; A = x * y A = 5 10 15 20 25 Two Vectors x = 1:5; y = 1:0.5:3; A = x * y Error Two Vectors (by element) x = 1:5; y = 1:0.5:3; A = x .* y A = 1 3 6 10 15 Problems with Two Variables 206_M5
Problems with Two Variables • Results of element-by-element calculations • All combinations of x and y • [X Y] = meshgrid(x,y) • A = X .* Y 206_M5
Example • Plot voltage vs time for various RC time constants 206_M5
Example • 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
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
Input / Output • Formatted Output • fprintf('format string', var, ...) • %f fixed point • %e exponential notation • %w.pf w=width, p=precision • \n linefeed (endl) • \t tab • Example • fprintf('The answer is %5.2f volts.\n', v) The answer is 5.25 volts. 206_M5
Input / Output • Formatted Output • Example • patient = 1:3; • temp = [98.6, 100.1, 99.2]; • hist = [patient;temp]; • fprintf('Patient %3.0f temp of %6.1f\n',hist) Patient 1 temp of 98.6 Patient 2 temp of 100.1 Patient 3 temp of 99.2 206_M5
Example Revisited % RC Time Constant ExamplewithUser 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
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
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
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
Example • Hand Example • 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
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
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
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
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
Relational Operators < less than <= less than or equal to > greater than >= greater than or equal to == equal to ~= not equal True and False 1 True 0 False Logical Operators & and | or ~ not Conditional Expressions 206_M5
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
if Statement if condition statements end if/else Statement if condition statements else statements end if/elseif/else Statement if condition statements elseif condition statements else statements end Selection Structures 206_M5
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
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
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
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
Summary • Problems with Two Variables • Input / Output • Functions • Control Structures 206_M5