Introduction to the Matlab Programming Enviroment

4 downloads 6807 Views 171KB Size Report
About Matlab: Matlab, short for Matrix Laboratory, is an interactive programming ..... available. Mastering MATLAB 7 by: Duane Hanselman & Bruce Littlefield is a.
Introduction to the Matlab Programming Environment Basic Concepts for New Users About Matlab: Matlab, short for Matrix Laboratory, is an interactive programming environment for the solution of a wide range of computational problems. Typical Engineering Applications Include: Post processing of “raw” data from sensors Physics applications such as Computational Fluid Dynamics (CFD) and Finite Element Method (FEM) Data visualization in the forms of plots, tables, contour diagrams and vector fields Computer Programming, Graphics and Animation This introduction to the software is intended for first time users and provides an explanation of core concepts and skills needed to gain proficiency using the software. Topics Covered Include: Using the Matlab Graphical User Interface Operators Command Line Interface Function and Script M-files Plotting Getting Started: In Computer lab ME302 Matlab can be started by selecting the option for the program from the windows start menu. Once the Graphical User Interface (GUI) appears a working directory can be specified using the current directory input line located at the top of the screen. To browse for a directory use the icon located to the right of the directory bar. Select a directory to work in.

1

The Matlab GUI:

The matlab GUI can be broken into a series of windows which can be ordered or deleted according to user preference. The four windows that appear by default are listed below and annotated above. A: Command Window The command window is used to issue commands to Matlab using standard command line interface B: Current Directory Displays files and folders located in the specified working directory C: Workspace Displays defined variables, their type and their contents D: Command History Displays a time ordered history of commands

2

File Operations: The command window can be used to perform file operations using the same commands found in DOS and UNIX operating systems. cd change directory ls , dir list directory contents copyfile(‘source’,’destination’) copy files movefile( … move files mkdir make directory delete remove file rmdir remove directory For example… Say we have DAQ system which writes data files to a known directory and we want to create a new directory to move the files into. If the data file is named results_a.dat and it is located in the directory /scratch/test1/test1_results We could issue the following commands: cd /scratch/test1/test1_results (Change Directory) ls (List Contents) This will allow us to see the directory contents ls >> results_a.dat results_b.dat results_c.dat Next we could issue cd .. (moves up one directory) mkdir test_results_a (makes a directory called test_results_a) copyfile( ‘/scratch/test1/test1_results/results_a.dat’, ‘/scratch/test1/test_results_a’) (Copies results_a.dat to test_results_a directory)

3

Operators: Matlab supports typical mathematical operators for the manipulation of numbers and variables. + - * / ^ E (Add, Subtract, Multiply, Divide, Exponent) Built-in Functions: Matlab has a wide array of built in functions Common: cos( value ) , exp( value ), log( value ), sqrt( value ), etc… Less Common: dft( value), fzero(function, value), eig( matrix ), etc… note: By default trigonometric functions return values corresponding to inputs IN RADIANS!

For Example… Enter the following into the command window: >> 4 + 4 Press Enter and the answer will appear. ans = 8 Also Try… 4*5, 4E5, cos(0.5), log(50), sqrt(100)

4

Variables: Variables in Matlab are assigned using “=” Always Use the Form: variable = value What is assigned on the right is stored in the left. Variables can take the form of names and can include numbers. Values can assign relationships between quantities, functions, and operations. Matlab has some built in values that you should be careful not to overwrite. i, j, pi, eps, flops, inf, NaN, nan, nargin, nargout, realmin, realmax Variables can also be used to store text strings. Strings are defined by placing characters between single quotes string = ‘string characters’ For example… a = 5, a1 = 5, zeta = 5 (Variables can be alphabetical or alphanumeric) c = a*a1 (Variables can be defined by operations of other defined variables) hyp = 30, theta = 25 x = hyp*cos((pi/180)*theta) y = hyp*sin((pi/180)*theta) r = sqrt(x^2 + y^2) (Variables can be defined by combinations of defined variables and defined functions) Firstname = ‘bob’ (Firstname is a string containing bob)

5

Matrices and Arrays One of the most powerful features of Matlab is its ability to perform matrix and array computations. An Array is simply a 1-dimensional matrix and can be defined using the following convention. Name = [ value1, value2, value3, … valuen] (Using Comma Delimitation) -orName = [ value1 value2 value3 … valuen] (Using Space Delimitation) Where the array has n values. A typical matrix consists of two dimensions i and j. Name = [i1j1, i1j2, i1j3 … i1jn ; i2j1, i2j2 i2j3 … i2jn ; i3j1, i3j2, i3j3 … i3jn] For Example… a = [1,2,3] b = [1,2,3; 4,5,6; 7,8,9] gives…

6

Working with Matrices Matlab offers many controls to easily manipulate matrices and perform matrix calculations. If we define two matrices as variables named mata and matb Some commonly used features would include… mata’ = transpose of mata det(mata) = determinant of mata inv(mata) = inverse of mata rref(mata) = row reduced form of mata eig(mata) returns eigen-matrix of mata mata(m,n) returns element mn of the m x n array mata(m,:) returns row m of matrix mata(:,n)

returns column n of a matrix

mata(m,n1:n2) returns elements between columns n1 and n2 in row m mata*matb = multiple of mata and matb mata + matb = addition of mata and matb mata – matb = subtraction of matb from mata c*mata = the multiple of mata and a scalar where c is the scalar mata^2 = the square of the matrix (mata*mata) This list is far from exhaustive. For a complete reference see the matlab help section titled Matlab >> Mathematics >> Matrices and Linear Algebra

7

Matrix Manipulation Matlab offers many features for the manipulation of matrices. If we have similar arrays with variable names a, b & c We can combine these arrays as follows: z = [a, b, c] We can assemble the arrays into a matrix as follows z = [a; b; c] where a, b and c will be “loaded” into separate rows We can insert an array as a portion of a matrix z(m,n) = [c] inserts the value c into the element mn of z w = [a, b, c] z(m,n1:n2) = w replaces values column n1 through n2 of row m with a, b and c For Example…

8

Piecewise Matrix Manipulation You might wonder how Matlab distinguishes between the elements of a matrix and the matrix itself. For instance, we know that squaring a matrix squares the total matrix. It is also possible to square all of the individual elements of the matrix. To perform this task the piecewise operator is used which is coded as a period preceding the desired operation. For example…

Piecewise manipulation is also available for ./ .\ and .*

9

M-files Obviously, it would not be very practical to interface Matlab solely by means of command line. If this were the case Matlab would be little more than a glorified graphing calculator. In actuality, scripts can be written for Matlab in a similar manner to the C programming language. There are two kinds of scripts that can be written for Matlab. Function M-files. A function takes a set of values, performs operations and returns a value. All of the built-in functions used in Matlab are stored as function M-files that come with the program. You can write your own functions. Script M-files. Script M-files are equivalent to a Matlab executable program. Matlab is different from traditional programming languages in a number of ways. There are no variable declarations in Matlab. You can declare a variable whenever you want. Matlab does not compile programs. Programs are executed line by line. Errors are found when the program reaches the line where the error is located. Some useful things to know…. The clear function erases all workspace variables. You typically want to make this the first operational line of your script. The % symbol is the Matlab symbol for a comment. Matlab supports typical programming features such as global variables and loops. It is a good idea to write programs using the m-file editor although scripts can also be written using any text editor such as notepad or emacs. The editor has useful debugging features.

10

Distinguishing Between Function and Script M-files The first line of an M-file distinguishes whether it is a function or a script. A function: Function output = functionname(input) -orFunction [output1 output2 … outputn] = functionname( input1 input2 … inputn)

A script: %Scriptname.m It is customary to make the first line a comment with the name of the script. T The following is an example of a simple function m-file…

11

The following is an example of a script m-file %cylstress.m %This script m-file calculates strain in a cylinder under %axial load as a function of applied force. %PARAMETERS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear all; %clear workspace %geometric dia = 1; % diameter [in] length = 10; % length [in] %material props Emod = 27000000; % Elastic Modulous [psi] %Load Force = 5000; % Axial Load [Lbf] %CODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% csa = (pi*(dia^2))/4; %[in^2] stress = Force / csa; %[ lbf / in^2 = psi ] strain = stress / Emod %[ psi / psi = dim ]

When naming the file it is important to use the extension .m A function must be named functionname.m where functionname is the name of the function.

12

Plotting Matlab has many built in plotting tools for the visualization of data. Plots can be 2-D such as a standard graph, contour plot or vector field. 3D plots exist in the form of vector plots, or response surfaces. The built-in plot command can be used to make a plot from two arrays of data. plot( x_array, y_array) Axes can be labeled using the following commands. xlabel( ‘label_string’) where label_string is the desired label for the x-axis ylabel( ‘label_string’) “ “ the y-axis title(‘label_string’) “” the title of the graph For example... This script will make a plot of the function y = x^2 % exampleplot.m %This script m-file plots the function y = x^2 xvals = linspace(0,10,100); % create array of values 0 to 10 w/ 100 points yvals = xvals.^2; % creates solution array plot(xvals, yvals); % plots x versus y grid on; % turns on grid marks xlabel('x values'); % label x-axis ylabel('y values'); % label y-axis title('y = x^2'); % label title

13

We can change the way that data is displayed by using a third argument in the plot command. If we issued plot(xvals, yvals, ‘o’) in the previous script the line connecting the data would be replaced by circles. Other options include: . x + * s d v ^ markers b g r c m y k color - : -. -line style If we used plot(xvals, yvals, go--) we would get green circles connected by a hash line. Other useful options for changing the way a graph is plotted include… axis([ x1 x2 y1 y2]) clips the graph ranges between x1, x2 and y1,y2 axis equal make increments in x equal to increments in y axis auto resets default graph options In addition to two dimensional plots Matlab has the capability of producing 3-D plots such as response surfaces of multivariable functions. If arr_a and arr_b represent 1 x n arrays a function of these arrays can be plotted as a response surface using the meshgrid and surf plot options. The command meshgrid converts the specified arrays into the matrix format needed for a 3-D plot. The command surf takes the values produced from the meshgrid of the converted arrays and produces a surface plot. The syntax for both commands is as follows: [ X , Y ] = meshgrid(arr_a, arr_b) Z = function… arr_a, arr_b some function of an and b surf(X,Y,Z)

This script will plot the function Z = sin(pi*X) + cos(pi*Y) %surf_example.m

14

%This script m-file generates a surface plot of Z = sin(pi*X) + cos(pi*Y) clear all % Clear Workspace x = linspace(1,10,100); % Create x array from 1 to 10 w/ 100 points y = linspace(1,10,100); % Create y array from 1 to 10 w/ 100 points [X, Y] = meshgrid(x,y); % Convert Arrays to m x n Matrix for Surface Plot Z = sin(pi.*X) + cos(pi.*Y); % Calculate multivariable funct Z = f(x,y) surf(X,Y,Z); % Generate a Surface Plot of the Function

This section concludes this introductory tutorial on Matlab basics. To learn about any of the topics discussed in greater detail a number of sources are available. Mastering MATLAB 7 by: Duane Hanselman & Bruce Littlefield is a great source. It is available through Pearson Education Inc.

15