Download presentation
Presentation is loading. Please wait.
Published byGerard Carter Modified over 9 years ago
1
EEE 242 Computer Tools for Electrical Engineering Lecture II Mustafa Karabulut
2
Lecture II Topics Control structures in Matlab ▫if, switch, for, while ▫Comparison operators Functions ▫Defining your own functions Basic plotting ▫Plotting in 2D
3
Programming-Flow Control Conditional Control — if, else, switch if, else, and elseif The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords—no braces or brackets are involved.
4
Programming-Flow Control Relational Operators Operator Description <Less than <=Less than or equal to >Greater than >=Greater than or equal to ==Equal to ~=Not equal to &and |or &&and (Short-circuit) ||or (Short-circuit)
5
Programming-Flow Control Conditional Control — if, else, switch if expression statements elseif expression statements else statements end
6
Programming-Flow Control Example 1 Use if, elseif, and else for Conditional Assignment %Create a matrix of 1. nrows = 4; ncols = 6; A = ones(nrows,ncols); %Loop through the matrix and assign each element a new value. Assign 2 on the main %diagonal, -1 on the adjacent diagonals, and 0 everywhere else. for c = 1:ncols for r = 1:nrows if r == c A(r,c) = 2; elseif abs(r-c) == 1 A(r,c) = -1; else A(r,c) = 0; end A
7
Programming-Flow Control Example 1 A = 2 -1 0 0 0 0 -1 2 -1 0 0 0 0 -1 2 -1 0 0 0 0 -1 2 -1 0
8
Programming-Flow Control Example 2 Compare Arrays Expressions that include relational operators on arrays, such as A > 0, are true only when every element in the result is nonzero. Test if any results are true using the any function. %% limit = 0.75; A = rand(10,1) if any(A > limit) disp('There is at least one value above the limit.') else disp('All values are below the limit.') end %% There is at least one value above the limit.
9
Programming-Flow Control Example 3 Test Arrays for Equality Compare arrays using isequal rather than the == operator to test for equality, because == results in an error when the arrays are different sizes. Create two arrays. %% A = ones(2,3); B = rand(3,4,5); % If size(A) and size(B) are the same, concatenate the arrays; otherwise, display a warning and return an empty array.
10
Programming-Flow Control Example 3 Test Arrays for Equality %% if isequal(size(A),size(B)) C = [A; B]; else disp('A and B are not the same size.') C = []; end %% A and B are not the same size.
11
Programming-Flow Control Example 4 Determine if Strings Match Use strcmp to compare strings. Using == to test for equality because results in an error when the strings are different sizes. %% reply = input('Would you like to see an echo? (y/n): ','s'); if strcmp(reply,'y') disp(reply) end %%
12
Programming-Flow Control Example 5 Evaluate Multiple Conditions in Expression Determine if a value falls within a specified range. %% x = 10; minVal = 2; maxVal = 6; if (x >= minVal) && (x <= maxVal) disp('Value within specified range.') elseif (x > maxVal) disp('Value exceeds maximum value.') else disp('Value is below minimum value.') end %% Value exceeds maximum value.
13
Programming-Flow Control for Execute statements specified number of times for index = values statements end for index = values, statements, end executes a group of statements in a loop for a specified number of times.
14
Programming-Flow Control Example 1 Assign Matrix Values Create a Hilbert matrix of order 10. %% s = 10; H = zeros(s); for c = 1:s for r = 1:s H(r,c) = 1/(r+c-1); end %%
15
Programming-Flow Control Example 2 Decrement Values Step by increments of -0.2, and display the values. %% for v = 1.0:-0.2:0.0 disp(v) end %% 1 0.8000 0.6000 0.4000 0.2000 0
16
Programming-Flow Control Example 3 Execute Statements for Specified Values Step by increments of -0.2, and display the values. %% for v = [1 5 8 17] disp(v) end %% 1 5 8 17
17
Programming-Flow Control Example 4 Repeat Statements for Each Matrix Column %% for I = eye(4,3) disp('Current unit vector:') disp(I) end %% result
18
Programming-Flow Control switch, case, otherwise Execute one of several groups of statements switch switch_expression case case_expression statements case case_expression statements... otherwise statements end switch switch_expression, case case_expression, end evaluates an expression and chooses to execute one of several groups of statements. Each choice is a case.
19
Programming-Flow Control Example 1 Compare Single Values Display different text conditionally, depending on a value entered at the command prompt %% n = input('Enter a number: '); switch n case -1 disp('negative one') case 0 disp('zero') case 1 disp('positive one') otherwise disp('other value') end %%
20
Programming-Flow Control Example 1 Compare Against Multiple Values Determine which type of plot to create based on the value of the string plottype. If plottype is either 'pie' or'pie3', create a 3-D pie chart. Use a cell array to contain both values. x = [12 64 24]; plottype = 'pie3'; switch plottype case 'bar' bar(x) title('Bar Graph') case {'pie','pie3'} pie3(x) title('Pie Chart') otherwise warning('Unexpected plot type. No plot created.') end
21
Programming-Flow Control try, catch try statements catch exception statements end try and catch blocks allow you to override the default error behavior for a set of program statements. If any statement in a try block generates an error, program control goes immediately to the catch block, which contains your error handling statements.
22
Programming-Flow Control while Repeat execution of statements while condition is true while expression statements end while expression, statements, end evaluates an expression, and repeats the execution of a group of statements in a loop while the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false.
23
Programming-Flow Control Example 1 Repeat Statements Until Expression Is False Use a while loop to calculate factorial(10). %% n = 10; f = n; while n > 1 n = n-1; f = f*n; end disp(['n! = ' num2str(f)]) %% n! = 3628800
24
Programming-Flow Control Example 2 Count the number of lines of code in the file magic.m. Skip blank lines and comments using a continue statement.continue skips the remaining instructions in the while loop and begins the next iteration. %% fid = fopen('magic.m','r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) || strncmp(line,'%',1) || ~ischar(line) continue end count = count + 1; end count fclose(fid); %%
25
Programming-Flow Control break Terminate execution of for or while loop break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.
26
Programming-Flow Control Example 1 Exit Loop Before Expression Is False Sum a sequence of random numbers until the next random number is greater than an upper limit. Then, exit the loop using a break statement. %% limit = 0.8; s = 0; while 1 tmp = rand; if tmp > limit break end s = s + tmp; End %%
27
Programming-Flow Control continue Pass control to next iteration of for or while loop continue temporarily interrupts the execution of a program loop, skipping any remaining statements in the body of the loop for the current pass. The continue statement does not cause an immediate exit from the loop as a break or return statement would do, but instead continues within the loop for as long as the stated for or while condition holds true. A continue statement in a nested loop behaves in the same manner. Execution resumes at the for or while statement of the loop in which the continue statement was encountered, and reenters the loop if the stated condition evaluates to true.
28
Programming-Flow Control end Terminate block of code, or indicate last array index end terminates for, while, switch, try, if, and parfor statements. Without an end statement, for, while, switch, try, if, and parfor wait for further input. Each end is paired with the closest previous unpaired for, while, switch, try, if, or parfor and serves to delimit its scope. end also marks the termination of a function, although in many cases it is optional. If your function contains one or more nested functions, then you must terminate every function in the file, whether nested or not, with end. This includes primary, nested, private, and local functions. The end function also serves as the last index in an indexing expression. In that context, end = (size(x,k)) when used as part of the kth index. Examples of this use are X(3:end) and X(1,1:2:end-1). When using end to grow an array, as in X(end+1)=5, make sure X exists first.
29
Programming-Scripts and Functions Overview There are two kinds of program files: Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.
30
Programming-Scripts and Functions Scripts When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot.
31
Programming-Scripts and Functions Scripts For example, create a file called magicrank.m that contains these MATLAB commands: %% % Investigate the rank of magic squares r = zeros(1,32); for n = 3:32 r(n) = rank(magic(n)); end r bar(r) %% You can run the code in magicrank.m using either of these methods: Type the script name magicrank on the command line and press Enter Click the Run button on the Editor tab
32
Programming-Scripts and Functions Functions Functions are files that can accept input arguments and return output arguments. The names of the file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.
33
Programming-Scripts and Functions Functions function Declare function name, inputs, and outputs function [y1,...,yN] = myfun(x1,...,xM) function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that accepts inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first executable line of the function. Save the function code in a text file with a.m extension. The name of the file should match the name of the first function in the file. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.
34
Programming-Scripts and Functions Functions-Examples Function with One Output Define a function in a file named average.m that accepts an input vector, calculates the average of the values, and returns a single result. function y = average(x) if ~isvector(x) error('Input must be a vector') end y = sum(x)/length(x); end Call the function from the command line. z = 1:99; average(z)
35
Programming-Scripts and Functions Functions-Examples Function with Multiple Outputs Define a function in a file named stat.m that returns the mean and standard deviation of an input vector. function [m,s] = stat(x) n = length(x); m = sum(x)/n; s = sqrt(sum((x-m).^2/n)); end Call the function from the command line. values = [12.7, 45.4, 98.9, 26.6, 53.1]; [ave,stdev] = stat(values)
36
Programming-Scripts and Functions Functions-Examples Multiple Functions in a File Define two functions in a file named stat2.m, where the first function calls the second. function [m,s] = stat2(x) n = length(x); m = avg(x,n); s = sqrt(sum((x-m).^2/n)); end function m = avg(x,n) m = sum(x)/n; end Function avg is a local function. Local functions are only available to other functions within the same file. Call function stat2 from the command line. values = [12.7, 45.4, 98.9, 26.6, 53.1]; [ave,stdev] = stat2(values)
37
Overview of Plotting Matlab has several functions to plot your data. Depending on your graphing style (bar, curve, one figure, two figures in one screen etc) and the nature of your data (2D or 3D), you should choose one of the appropriate functions. plot(x, y) – Draws 2D plots plot3(x, y, z) – Draws 3D plots plotyy(x1, y1, x2, y2) – Plots two graphs in one axis pair mesh(X, Y, Z) and surf(X, Y, Z) – Draws 3D surface plots
38
Overview of Plotting Today, you will learn the following functions: plot(x, y) – Draws 2D plots title(‘…’), xlabel(‘…’), ylabel(‘….’) – Changes title of the plot and axis figure / figure(n) – Open new figure or select one of the existing figures close all/close (n) – Close all figures or a selected figure hold on – add current plot to the existing figure axis – Limits the axis values or enables/disables them subplot – display more than one figure in one figure window
39
Using Basic Plotting Functions Creating a Plot The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. For example, these statements use the colon operator to create a vector of x values ranging from 0 to 2π, compute the sine of these values, and plot the result: x = 0:pi/100:2*pi; y = sin(x); plot(x,y)
40
Using Basic Plotting Functions Creating a Plot Open a new.m file and type the following then save and run the script x = 0:pi/100:2*pi; y = sin(x); plot(x,y) Label the axes and add a title. The characters \pi create the symbol π. xlabel('x = 0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function','FontSize',12)
41
Using Basic Plotting Functions
42
Overview of Plotting Using Plotting Tools and MATLAB Code You can enable the plotting tools for any graph, even one created using MATLAB commands. For example, suppose you type the following code to create a graph: clc,clear all, close all %First generate a time series in an interval t = 0:0.01:20; % time interval is defined between 0 and 1 with stepsizes 0.001 y = 2*sin(5*t)+5*exp(0.1*t).*cos(3*t); plot(t,y) title('2sin(5t)+5exp(0.1t)cos(3*t)') xlabel('X Axis') ylabel('Y Axis')
43
Example Figure window y axis x axis Line plot represents data Toolbar arranges shortcut
44
Overview of Plotting
45
Using Basic Plotting Functions Plotting Multiple Data Sets in One Graph Multiple x-y pair arguments create multiple graphs with a single call to plot. For example, these statements plot three related functions of x, with each curve in a separate distinguishing color: x = 0:pi/100:2*pi; y = sin(x); y2 = sin(x-.25); y3 = sin(x-.5); plot(x,y,x,y2,x,y3) The legend command provides an easy way to identify the individual plots: legend('sin(x)','sin(x-.25)','sin(x-.5)')
46
Using Basic Plotting Functions
47
Specifying Line Styles and Colors It is possible to specify color, line styles, and markers (such as plus signs or circles) when you plot your data using the plot command: plot(x,y,'color_style_marker') color_style_marker is a string containing from one to four characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker type. The strings are composed of combinations of the following elements
48
Using Basic Plotting Functions Specifying Line Styles and Colors plot(x,y,'color_style_marker')
49
Using Basic Plotting Functions Plotting Lines and Markers x1 = 0:pi/100:2*pi; x2 = 0:pi/10:2*pi; plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
50
Using Basic Plotting Functions Plotting Lines and Markers If you specify a marker type but not a line style, only the marker is drawn. For example, plot(x,y,'ks') plots black squares at each data point, but does not connect the markers with a line. The statement plot(x,y,'r:+') plots a red-dotted line and places plus sign markers at each data point.
51
Using Basic Plotting Functions Plotting Lines and Markers
52
Using Basic Plotting Functions Adding Plots to an Existing Graph The MATLAB hold command enables you to add plots to an existing graph. When you type hold on Now MATLAB does not replace the existing graph when you issue another plotting command; it adds the new data to the current graph, rescaling the axes if necessary.
53
Using Basic Plotting Functions Figure Windows Graphing functions automatically open a new figure window if there are no figure windows already on the screen. If a figure window exists, it is used for graphics output. If there are multiple figure windows open, the one that is designated the "current figure" (the last figure used or clicked in) is used To make an existing figure window the current figure figure(n) where n is the number in the figure title bar. Clearing the Figure for a New Plot clf clears the current figure
54
Using Basic Plotting Functions Displaying Multiple Plots in One Figure The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper. Typing subplot(m,n,p) partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered along the first row of the figure window, then the second row, and so on. For example, these statements plot data in four different subregions of the figure window:
55
Using Basic Plotting Functions Displaying Multiple Plots in One Figure Type the following t = 0:pi/10:2*pi; % [X,Y,Z] = cylinder(4*cos(t)); subplot(2,2,1); plot(t,2*sin(t)) subplot(2,2,2); plot(t,sin(2*t)) subplot(2,2,3); plot(t,cos(t)) subplot(2,2,4); plot(t,-sin(t))
56
Using Basic Plotting Functions
57
Controlling the Axes The axis command provides a number of options for setting the scaling, orientation, and aspect ratio of graphs. Setting Axis Limits By default, MATLAB finds the maxima and minima of the data and chooses the axis limits to span this range. The axis command enables you to specify your own limits: axis([xmin xmax ymin ymax]) or for three-dimensional graphs, axis([xmin xmax ymin ymax zmin zmax]) Use the command axis auto to enable automatic limit selection again.
58
Using Basic Plotting Functions Setting Axis Visibility You can use the axis command to make the axis visible or invisible. axis on makes the axes visible. This is the default. axis off makes the axes invisible. Setting Grid Lines The grid command toggles grid lines on and off. The statement grid on turns the grid lines on, and grid off turns them back off again.
59
Using Basic Plotting Functions Adding Axis Labels and Titles The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command adds a title at the top of the figure and the text function inserts text anywhere in the figure. t = -pi:pi/100:pi; y = sin(t); plot(t,y) axis([-pi pi -1 1]) xlabel('-\pi \leq {\itt} \leq \pi') ylabel('sin(t)') title('Graph of the sine function') text(1,-1/3,'{\itNote the odd symmetry.}')
60
Using Basic Plotting Functions
61
Saving Figures Save a figure by selecting Save from the File menu. This writes the figure to a file, including data within it, its menus and other uicontrols it has, and all annotations (i.e., the entire window). If you have not saved the figure before, the Save As dialog displays. It provides you with options to save the figure as a FIG-file or export it to a graphics format, as the following figure shows. To save a figure using a standard graphics format for use with other applications, such as TIFF or JPG, select Save As (or Export Setup, if you want additional control) from the File menu.
62
Using Basic Plotting Functions Saving Workspace Data You can save the variables in your workspace by selecting Save Workspace As from the figure File menu. You can reload saved data using the Import Data item in the figure File menu. MATLAB supports a variety of data file formats, including MATLAB data files, which have a.mat extension. Generating M-Code to Recreate a Figure You can generate MATLAB code that recreates a figure and the graph it contains by selecting Generate M-File from the figure File menu. This option is particularly useful if you have developed a graph using plotting tools and want to create a similar graph using the same or different data
63
End of lecture 2 Thank you for listening See you next week
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.