0% found this document useful (0 votes)
63 views

Basics of Using Matlab: (S. Tewksbury)

This document provides an overview of the basics of using MatLab, including: 1) Type declarations do not require specifying data types and MatLab is type sensitive. 2) MatLab uses standard arithmetic operators and has special operators for matrices and complex numbers. 3) Functions are accessed using "help" and include elementary, special, and matrix functions. 4) Programs are written using expressions, input/output, and conditionals like if/else statements similar to C syntax but without curly braces.

Uploaded by

Suresh Sana
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Basics of Using Matlab: (S. Tewksbury)

This document provides an overview of the basics of using MatLab, including: 1) Type declarations do not require specifying data types and MatLab is type sensitive. 2) MatLab uses standard arithmetic operators and has special operators for matrices and complex numbers. 3) Functions are accessed using "help" and include elementary, special, and matrix functions. 4) Programs are written using expressions, input/output, and conditionals like if/else statements similar to C syntax but without curly braces.

Uploaded by

Suresh Sana
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Basics of Using MatLab

(S. Tewksbury)

1. GETTING STARTED....................................................................................................................................................2 1.1 TYPE DECLARATIONS: ................................................................................................................................................2 1.2 ARITHMETIC OPERATORS ...........................................................................................................................................2 1.3 FUNCTIONS ..................................................................................................................................................................2 1.4 EXPRESSIONS ..............................................................................................................................................................2 1.5 INPUT AND OUTPUT ....................................................................................................................................................3 1.6 CONDITIONALS ...........................................................................................................................................................3 2. MOVING ON .................................................................................................................................................................6 2.1 MATRICES FOR SOLVING SETS OF LINEAR EQUATIONS ............................................................................................6 2.2 MATRIX INVERSION U SING THE "INV(A)" FUNCTION AND THE "A" STRUCTURE ...................................................7 2.3 USING "M- FILES" AS PROGRAMS ................................................................................................................................8 2.4 VECTORS AND G ENERATING PLOTS.........................................................................................................................11 2.4a Setting Up ..........................................................................................................................................................11 2.4b Plotting (Single Plot) ........................................................................................................................................11 APPENDIX A: SAMPLE PROGRAM FOR RLC TRANSIENT ANALYSIS......................................................15

MatLab is a premier professional mathematics software package. In its basic form (lacking any of the many toolboxes associated with the core program), powerful capabilities in solving of linear equations, solving of differential equations, solving of integral equations, and solutions to a wide range of matrix-related problems are provided. These basic capabilities are greatly enhanced by use of "toolboxes" providing topic specific solutions for far more complex problems in a wide range of engineering fields (ranging from areas such as bioengineering, medical imaging, and many others). Also associated with MatLab is a companion simulation software package called Simulink. Simulink provides the ability to effectively model and simulate complex systems in many fields. Knowledge of a programming language (e.g., JAVA, C++) is a primary engineering skill in today's world of computer-intensive analysis. MatLab captures much of the flavor of a programming language (C-language based) but designed specifically to handle mathematical problems. Other mathematics software packages include Mathcad and Mathematica,. Each has specific advantages for specific problems. For example, MatLab highlights matrix-based problems whereas Mathematica highlights complex mathematical equations. Note - May Be Important: As in any program, you can enter into a loop that never exits. After typing an instruction such a "while(done>0.) in the command window, MatLab has started to run the loop. You may not be able to get out. The usual Unix escape sequence (control key and the "c" key pressed simultaneously) will cause the stuck program to terminate. This may have happened to one of the students in the Friday class whose MatLab would not run anything.

1. Getting Started
1.1 Type declarations: MatLab does not require specification of data types (e.g., as in the case of C++). MatLab is type sensitive (capitals are not the same as lower case). Numbers include integers (e.g., 7, 10), decimal numbers (e.g., 7.4, 2.76), and scientific notation (e.g., 2.6e-3). Imaginary numbers (you can use either "i" or "j" as a suffix to represent the imaginary part) are directly supported (e.g., 2.7 + 1.6i). Note that the "i" or "j" is a suffix and that there is no operation between the number and "i". You can also use "i" and "j" as variables but variables never appear as suffixes to numbers. MatLab was developed to be particularly effective in solving "Mat"rix problems and that foundation continues. Much of the difference between MatLab and standard programming languages relates to this built in capability (some might say dependence on) matrix formats. MatLab also is different from standard programming languages such as C++ in being able to be used much like a calculator (no stored user program) in addition to being able to execute programs (called "m files"). The Manual: While in the Command Window, select "Help" from the MatLab main window. On a Mac, one of the options under the "Help" pulldown menu is "MatLab Help", which if selected brings up a browsable indexed manual. 1.2 Arithmetic operators MatLab uses the standard mathematical operators. + * / ^ \ Addition (C = A + B) Subtraction (C = A - B) Multiplication (C = A*B) Division (C = A/B) Power (C = A^3) Complex conjugation transpose (Matrix stuff) Left division is a special operation (used with matrices).

MatLab also the following operators.

1.3 Functions You can get lists of available functions using "help" as follows Type "help elfun" to obtain list of elementary functions Type "help specfun" to obtain list of more advanced functions Type "help elmat" to obtain list of matrix functions.

1.4 Expressions Writing a MatLab program is much like writing any program. Example expressions include

%Example A rho = (1+sqrt(5))/2 rho = 1.6180

%Example B a = abs(3+4i) a = 5

%Example C a = abs(3+4i); b = a b = 5

%Example D z = sqrt(besselk(4/3,rho-i)) z = 0.3730+ 0.3214i

In these examples, the statements preceded by "%" are comment lines. The statements in red are the statement you type into the MatLab command window. The lines in green are the responses from MatLab displayed in the command window. Example B and C illustrate one important rule regarding the termination of instruction lines. If the instruction is terminated with a semicolon (as in the instruction "a = abs(3+4i);" in example C), the instruction is executed and the value of the variable on the right side is saved (and can be referenced in later instructions). However, the terminating semicolon prevents the display of the value following the instruction. If the instruction is not terminated with a semicolon (as in the instruction "b = a" in example C and for all the instructions in the other examples), the value assigned to the variable is displayed (shown in green). You can regard the semicolon as a means of controlling what is displayed and what is not displayed. 1.5 Input and Output You can enter the value of a variable with the basic input statement (which includes text that will display if desired). For example, to input a value of the variable x, the input statement is x = input('Enter the value of x '); If you want to input a matrix such as [1,2;3,4], you simply type in this form. If you want to enter a character (e.g., the character y), you must use the program format for characters. In response to the instruction done = input('Enter y to continue, n to stop '); you would need to respond with either 'n' or 'y' since characters are specified by single quotation marks. Values of variables can be "printed" to your display by leaving the semicolon off of the end of an instruction. To display text, use the "display" command, e.g., display('Here is the text '). 1.6 Conditionals The "MatLab Help" manual (under the "Help" pulldown menu) provides information on conditionals under the "Programming" -> "Basic Program Components" -> Program Control Statements heading of its Contents window. You will find the standard C-languaage control

statements ("if," "switch" "for," "while,", "continue," and "break"). The syntax for these commands is however different in MatLab. The general forms for MatLab and C-programs is shown in the table below.

MatLab Syntax
Starting Control Instruction Instruction Instruction ..... end Statement 1 2 3

C-Language Syntax
Starting Control { Instruction Instruction Instruction ..... } Statement 1 2 3

The various control structures you are most likely to use are "while", "if" and its variants, and "for". These are illustrated below. % ********* the while instruction ************************* while (done > 0.) % First insruction for while loop % Other instructions % Instruction changing "done" so that loop terminates. % Last instruction for while loop end % ********* the if instruction *********************** if (test < 0) % First instruction for the case test less than zero % ..... % Last instruction for this case end % ********* the if, else sequence ********************* if (test < 0) % First instruction for the case test less than zero % ..... % Last instruction for this case else % First instruction for other values of test % ..... % Last instruction for this case end % ********* the if, elseif sequence ******************* if (test < 0) % First instruction for the case test less than zero % ..... % Last instruction for this case

elseif (test > 27) % First instruction for the case test greater than 27 % ..... % Last instruction for this case end % ********* the if, elseif, else sequence ************* if (test < 0) % First instruction for the case test less than zero % ..... % Last instruction for this case elseif (test > 27) % First instruction for the case test greater than 27 % ..... % Last instruction for this case else % First instruction for other values of test % ..... % Last instruction for this case end % ********* the for sequence ************* for k = 1:2:100 % First instruction of for loop % Other instructions % Last instruction of for loop end

The "for loop" has the general form "for k = Nstart, DeltaN, Nstop". The first value of k is Nstart, the second is Nstart + DeltaN, etc. until k is equal to or greater than Nstop.

2. Moving On
2.1 Matrices for Solving Sets of Linear Equations In the circuit analysis problems involving Kirchoff's current and voltage equations, you had to solve sets of linear equations. MatLab will do this for you rather easily. Consider the following equations.

3w + 2x + 5y + 4z = 4 5w + 1x + 8y ! 2z = 3 2w ! 4 x + 6y ! 7z = 5 9w + 3x ! 3y + 4z = 7 or, in matrix form "3 2 5 4 % "w% "4% $ ' $ ' $ ' $5 1 8 !2' ( $ x ' = $ 3' $2 !4 6 !7' $ y ' $5' $ ' $ ' $ ' #9 3 !3 4 & # z & #7&
Letting A be the 4x4 matrix, X be the column vector [w,x,y,z] and y be the column vector [4,3,5,7], the equation can be writting A*X = Y. Use the matrix A, and vector Y to solve for X A * X = Y . Multiply this equation by A!1 = 1/ A using

(A

!1

" A) " X = X = A!1 *Y giving

X = A!1 "Y
The MatLab program solving the above is illustrated below with two examples. 2.2 Matrix Inversion Using the "inv(A)" Function and the "A\" Structure In the copy below from the Command Window of MatLab, I have changed the text coloring. Red (following the prompt ">>") is an input you type. Blue is a result displayed (since I did not terminate the Red lines with a semicolon). The "%" starts a comment (ending at the end of the line).
>> A = [3,2,5,4; 5,1,8,-2; 2,-4,6,-7; 9,3,-3,4] A = 3 2 5 4 5 1 8 -2 2 -4 6 -7 9 3 -3 4 >> Y = [4;3;5;7] Y = 4 3 5 7 >> B = inv(A) %This computes the inverse of A B = 0.0189 -0.0325 0.0801 0.1051 -0.3273 0.4429 -0.3477 -0.0597 0.0983 0.0310 0.0166 -0.0537 0.2766 -0.2358 0.0930 0.0181 >> X = B*Y X = 1.1141 -2.1368 0.1935 0.9909 >> % Above gives solution for w, x, y, and z.

>> >> >> >> >> >> X2

%Another form (looks strange) to multiply column vector Y by the %inverse of A is X2 = A\Y = 1.1141 -2.1368 0.1935 0.9909

>>

2.3 Using "m-files" as Programs Although you can work directly in the command window, typing in instructions and observing results, this is quite inconvenient for all but the simplest problems. MatLab allows you to write and store a program (and to create your own functions - a topic not considered here). The programs are called "m-files" and to create them you start with the MatLab editor.

Just below the "File" pulldown menu of MatLab, you will see an icon representing a blank sheet of paper. Clicking on this opens the MatLab editor, shown below with the simple program to calculate the solution to the linear equations given earlier in Section 2.2.

Next you save the program created in the editor. I am using "Save As" (Macintosh) and saving the program as "example1.m" in a directory called "Programs" located in the MatLab folder, as shown in the figure below.

By default, my system stored user files in the main MatLab folder, where they were soon lost among the normal MatLab files/directories. You should create a directory to hold your m-files. You must ensure that any directory you create to hold your m-files is in your path list. Create a folder for your programs in the main MatLab folder where the executable is located. Next, under the "File" pulldown menu, click on "Add Path" and enter the path to the folder you created. By doing this, MatLab will include your new folder when looking for a named m-file (see discussion after figure below). Now that we have a stored program, you can close the editor window and return to the command window in the main MatLab window. You run the program by typing its name ("example1" for the program above) in the MatLab command window. The screen shot below shows the running of the program.

Since the program did not specify the number of linear equations being solved, I can use it for any set of linear equations. Try running it for a set of 6 linear equations and you will see the advantage of the program. Or if you are patient at typing in the matrix and column vector, perhaps you would like to solve 100 simultaneous equations in 100 unknowns (far too much typing for me).

2.4 Vectors and Generating Plots Think about a plot of the function y = f(x) obtained using your calculator. For values of x, you calculate y and draw a dot on the plot for that point. You then connect the dots. This is done in MatLab by saying that the values of x used are a vector. For example, points between 0 and 10 with spacing 2 would correspond to the vector x = [0,2,4,6,8,10]. Given each value of x, you would calculate the corresponding value for y. MatLab can do this in a simple form such as the function f(x) = 2*x + 1.5. This would be written, with the vector x defined as above as follows. y = 2*x + 1.5. This would generate a vector y with 6 components, each component of y (e.g., y[3]) obtained from the corresponding component of x (e.g., x[3]) according to y[k] = 2*x[k] + 1.5. With these vectors (named y and x) you plot by simply saying (in an instruction) plot(x,y). The plot would be based on the six points calculated. 2.4a Setting Up Resetting: All variables assigned remain assigned unless changed. Clear all history: cla reset Clear plot: clf Or use "edit" pull-down menu to clear command window and/or command history. To initialize a vector Y to a linearly spaced set of N values starting at A and ending at value B, Y = linspace(A, B, N); To initialize a vector & to a logarithmically spaced set of N values starting at 10 A and ending at value 10 B , Y = logspace(A,B,N). To set up a vector Y with values starting at A, ending at B, and separated by dV, Y = A:dV:B To set up a vector Y with N values all equal to zero or one, use Y = zeros(1,N) or Y = ones(N,0)

Setting Up a Vector:

2.4b Plotting (Single Plot) Assume that you want to plot two functions y = f(x) and z = g(x). The following basic steps hold. First, you must set up x, y, and z as vectors (one component for each point plotted). For example, x = linspace(0,100,200); y = x; %This merely sets y to be a vector of the same size as x. z = x; plot(x,y,x,z);

You can change the color and type of plot lines Color Style Options y m c r g b w k yellow magenta cyan red green blue (default) white black Line Style Options - solid -- dashed : dotted -. dash-dot

plot(x,y,'r--') plot(x,y,'r--', x,z,'b:') Legend: After doing all the plots, use legend('string 1', 'string 2', etc). This will give a text statement with line types associating types with each legend, in the order in which the plot was done. Labeling Axes: You can label the x and y axes using xlabel('time') ylabel('variable') Labeling Plot title('Plot of y vs x') Adding text to label plot curves: After this command executes, you need to click on the graph window to place the text gtext('text') Overlay Plots: If you again use the plot command, it will normally erase what you have done and start over. Use hold on to prevent this erasing to allow overlay plots. plot(x,y,x,z) and plot(x,y) hold on plot(x,z) will have the same effect. Multiple Plots: Here, you will be drawing multiple plots. subplot(m,n,p) divides window into an m x n array of plots and places the next plot in the pth subwindow. Obtain p by counting first across row, then down to next row.

The figure below shows the result of running the program at the end of these notes and the resulting plots generated. The program plots the currents and voltages for either series RLC circuits with a voltage source or parallel RLC circuits with a current source. From the values of R, L, and C entered, it determines the values of ! and " 0 , determines whether ! > " 0 or ! < " 0 and presents you with the time constant associated with the circuit (letting you choose some

multiple of the time constant for your plot). The values of R, L, and C that I entered gave a value of ! less than " 0 , leading to the solutions with the sinusoidal variation discussed in class.

The plots of the loop current, along with the various voltages of the resistor, capacitor, and inductor, are shown in the next figure.

Appendix A: Sample Program for RLC Transient Analysis


The program below illustrates several of the points made above regarding MatLab. You should be able to "read" this program and understand where the basic calculations are being made as well as how the various cases (series vs parallel, overdamped vs underdamped) are handled.
display('RLC Transient Response') done = 1.; while (done > 0.) cla reset; clf; type = input('Enter positive number for series RLC circuit, negative for parallel RLC circuit)'); np = input('Enter number of points in plot '); Res = Cap = Ind = % Res input('Enter Resistance (ohms) '); input('Enter Capacitance (Farads) '); input('Enter Inductance (Henries) '); = 0.6*sqrt(Ind/(4*Cap))

wzero = sqrt(1/(Ind*Cap)) if(type > 0) A = 1/Ind; % Res = 0.25*sqrt(4*Ind/Cap) B = Res; alfa = Res/(2*Ind) display('You will be working with a series RLC circuit with voltage source) '); Xa = input('Enter source voltage (volts) for time < 0 '); Xb = input('Enter source voltage (volts) for time > 0 '); end if (type < 0) A = 1/Cap; % Res = 4.0*sqrt(Ind/(4.*Cap)) B = 1/Res; alfa = 1/(2*Res*Cap) display('You will be working with a parallel RLC circuit with current source) '); Xa = input('Enter source current (amps) for time < 0 '); Xb = input('Enter source current (amps) for time > 0 '); end

if(alfa > wzero) display('Alpha greater than natural frequency, OK '); S1 = alfa + sqrt(alfa*alfa - wzero*wzero); S2 = alfa - sqrt(alfa*alfa - wzero*wzero); tcons2 = 1/S2; display('Larger time constant is ');

display (tcons2); tcons1 = 1/S1; display('Shorter time constant is '); display (tcons1) tmax = input('Enter maximum time for plot '); time = linspace(0,tmax, np); YS1 = linspace(0,tmax, np); YS2 = linspace(0,tmax, np); Ytot = linspace(0,tmax, np); Xres = linspace(0,tmax, np); XLorC = linspace(0,tmax, np); Xother = linspace(0,tmax, np); Xtotal = linspace(0,tmax, np); for k=1:np VS1 = ((Xb - Xa)/(S1 - S2)); VS2 = ((Xb - Xa)/(S1 - S2)); YS1(k) = A*VS1*exp(-S1*time(k)); YS2(k) = A*VS2*exp(-S2*time(k)); Ytot(k) = YS2(k) - YS1(k); Xres(k) = B*Ytot(k); XLorC(k) = VS1*S1*exp(-S1*time(k)) - VS2*S2*exp(-S2*time(k)); Xother(k) = Xb - Xres(k) - XLorC(k); Xtotal(k) = Xres(k)+XLorC(k)+Xother(k); end subplot(2,1,1); plot(time, YS1, time, YS2, time, Ytot), grid; legend('exp(-S2*t) term', 'exp(-S1*t) term', 'Combined Terms'); xlabel('Time'); hold on; if(type > 0) ylabel('Loop Current'); title('Series RLC Circuit with Voltage Source'); end if(type < 0) ylabel('Node Voltages'); title('Parallel RLC Circuit with Current Source'); end subplot(2,1,2); plot(time, Xres, time, XLorC, time, Xother, time, Xtotal), grid; axis([0,1.1*tmax,0,1.2*Xb]); xlabel('Time'); if(type > 0) ylabel('Component Voltages'); title('Series RLC Circuit with Voltage Source');

legend('Resistor voltage', 'Inductor voltage', 'Capacitance Voltage', 'Sum of these voltages'); end if(type < 0) ylabel('Component Currents'); title('Parallel RLC Circuit with Current Source'); legend('Resistor current', 'Capacitor current', 'Inductor current', 'Sum of these currents'); end end

if(alfa < wzero) display('Alpha less than than natural frequency, OK '); Wn = sqrt(wzero*wzero - alfa*alfa); tcons = 1/alfa; display('Decay time constant is '); display (tcons); tmax = input('Enter maximum time for plot '); time = linspace(0,tmax, np); Ytot = linspace(0,tmax, np); Xres = linspace(0,tmax, np); XLorC = linspace(0,tmax, np); Xother = linspace(0,tmax, np); Xtotal = linspace(0,tmax, np); for k=1:np VS1 = (Xb - Xa)/Wn; Ytot(k) = A*VS1*exp(-alfa*time(k))*sin(Wn*time(k)); Xres(k) = B*Ytot(k); XLorC(k) = VS1*exp(-alfa*time(k))*(Wn*cos(Wn*time(k)) alfa*sin(Wn*time(k))); Xother(k) = Xb - Xres(k) - XLorC(k); Xtotal(k) = Xres(k)+XLorC(k)+Xother(k); end subplot(2,1,1); plot(time, Ytot), grid; xlabel('Time'); %hold on; if(type > 0) ylabel('Loop Current'); title('Series RLC Circuit with Voltage Source'); legend('Loop current'); end

if(type < 0) ylabel('Node Voltages'); title('Parallel RLC Circuit with Current Source'); legend('Node voltage'); end subplot(2,1,2); plot(time, Xres, time, XLorC, time, Xother, time, Xtotal), grid; xlabel('Time'); if(type > 0) ylabel('Component Voltages'); title('Series RLC Circuit with Voltage Source'); legend('Resistor voltage', 'Inductor voltage', 'Capacitance Voltage', 'Sum of these voltages'); end if(type < 0) ylabel('Component Currents'); title('Parallel RLC Circuit with Current Source'); legend('Resistor current', 'Capacitor current', 'Inductor current', 'Sum of these currents'); end end done = input(' enter negative number to stop, postive number to repeat '); end

You might also like