Sunteți pe pagina 1din 10

ME /AE 408

Introduction to MATLAB
MATLAB (Matrix Laboratory) is an interactive software for doing vector and matrix manipulations and general numerical computations. Because matrix and vector manipulations are essential parts in the Finite Element Method, FEM is an ideal candidate for using MATLAB. A summary of MATLAB commands are given below with examples. 1. Getting Started In MATLAB, command line is indicated by >>.This prompt receives a user command and processes it providing the output on the next line. The help menu in MATLAB can be invoked either by typing help at the command prompt or by using the help option provided on the toolbar. >> help Similarly invoking quit/exit command exits the MATLAB at any time. >> exit 2 Variables 2.1. Assigning values Variables in MATLAB are created using assignment statements. >> x = 10 Variable names can be combination of letters, digits and underscores but must begin with letters. It should be noted that MATLAB distinguishes between uppercase and lowercase characters, so X and x are not the same variables. 2.2 Suppressing the Output A semicolon at the end of any command in MATLAB suppresses the output. 2.3 Built in functions MATLAB has many built-in functions which can be readily used. Some of them are tabulated below: symbol Cosine Sine Tangent Arc cosine Arc sine Arc tangent Hyperbolic sine Hyperbolic cosine Hyperbolic tangent Complex conjugate 1 Description Exponential Square root Natural logarithm Common logarithm Absolute value Signum function Maximum value Minimum value Round towards +1 Round towards -1

cos(x) sin(x) tan(x) acos(x) asin(x) atan(x) sinh(x) cosh(x) tanh(x) conj(x)

exp(x) sqrt(x) log(x) log10(x) abs(x) sign(x) max(x) min(x) ceil(x) floor(x)

2.4 Other useful commands Here are few additional useful commands: clear or clear all removes all variables from the workspace Who display a list of the variables currently in the memory whos will give more details which include size, space allocation, and class of the variables clc clears the Command Window ctrl-c aborts a MATLAB computation To continue a line, type . . .

3. Vectors & Matrices 3.1 Defining Matrices In MATLAB, matrix is entered row by row where rows are separated by semicolons and elements in each row are separated by comma (,) or space. Example: >> A = [1, 3, 10; 7 5 9; 6 8 3] The output appears in the next line as below. A= 1 7 6

3 5 8

10 9 3

The rows can also be separated by entering the next row in a new line as shown below: >> B = [ 2 5 6 901 847] gives the output as, B= 2 9 8 5 0 4 6 1 7

3.2 Basic Mathematical Functions Operator + * / ^ Examples: >> A + B ans = 3 16 14 8 16 5 10 12 10 Explanation Addition Subtraction Multiplication Division Transpose Power

>> A B ans = -1 -2 4 -2 5 8 -2 4 -4 >> A * B ans = 109 131 108 45 79 71 110 42 65

3.3 Basic Matrix Functions Symbol Size det inv diag trace eye(n) zeros(i,j) eig rand(i,j) Description Dimensions of matrix Determinant of matrix Inverse of matrix Diagonal of a matrix Summation of diagonal elements of matrix Identity matrix (n x n) Zero matrix (i x j) Eigen values and eigen vectors Generates i x j matrix with random numbers

Examples: >>size(A) ans = 3 3 >>det(A) ans = 302 >>inv(A) ans = -0.1887 0.2351 -0.0762 0.1093 -0.1887 0.2020 0.0861 0.0331 -0.0530 >>diag(A) ans = 1 5 3 >>trace(A) ans = 9 >>eye(3) ans = 1 0 0 0 1 0 0 0 1

>>zeros(2,3) ans = 0 0 0 0 0 0

>>[C L] = eig(A) where the columns of C matrix give the Eigen vectors, and the values of L matrix gives Eigen values. The output shows the following results: C= -0.4692 -0.8618 -0.8677 -0.6754 0.4374 0.1982 -0.5690 0.2569 0.4560 L= 17.4446 0 0 0 -3.5041 0 0 0 -4.9404 3.4 Extracting bits of matrices In many problems, we will come across the need of extracting few columns or rows or sub matrices from the main matrix. Colon is a useful operator in doing this. The following sections explain how to use this operator. 3.4.1 Extracting columns of matrix >>A (:,3) ans = 10 9 3 which is the third column of the matrix. 3.4.2 Extracting rows of matrix: >>A (2,:) ans = 7 5 9 which is the second row of the matrix 3.4.3 Extracting sub-matrices: If we want the first two rows and the last two columns of the matrix, then the colon operator can be used as follows: >>A(1:2,2:3) ans = 3 5 10 9

4. Programming in MATLAB Compared to other softwares, programming in MATLAB is simple and easy. The operators or statements used here are similar to other commonly used programming languages. 4.1. Logical & Relational Operators Some of the logical and relational operators are given below: Symbol </> <=/>= == ~= ~ & | 4.2 Loop and Logical Statements if else if, else for while break A conditional statement Used along with if command Loop command Loop command with conditional statement Breaks the loop when a condition is met. Description Less than/Greater than Less than / Greater than or equal to Equal to Not equal to Not And Or

4.3 Script/m-files It is very convenient to be able to save the programs for later use. MATLAB allows you to edit and save programs in text files called m-files (since the files should have an extension of .m). Once the file is created, it can be called and executed by simply typing the file name at the command prompt. >>myprogram.m 4.4 Function subroutines/m-files These files are similar to script files except that, these are started with a header: Function [a,b,c] = myprogram(x,y,z) where a, b, c are output variables and x, y, z are input variables. Input variables can be either numerical values or the actual variables where as, the output variables can be any variables. In writing the subroutines, it should be remembered that the function name and the file name should be the same. For example, the above function should be saved in the file, myprogram.m. Once the function is created, it can be called as: >> [a,b,c] = myprogram(x,y,z) or >> [a,b,c]=myprogram(2,8,5)

Note: 1. The function file should be in the same directory that the MATLAB uses in doing the programming or should be added to the current one. Example: Subroutine for the function g ( x) = Function [g] = sample(x) g = 1/ (1-x)3 and the function can be called as: >> y = sample(8) 2. Adding comment statements (statements that start with %) at the beginning of the function files will make the program clear for understanding after a period of time. Example: Function [a,b,c] = sub(x,y,z) % To solve % Input Variables %x= %y= %Output Variables %a= %b= 4.5 Input-Output Functions These functions make MATLAB user-friendly. The input command is used to receive an input from the user. The display command displays the text or numerical values on the screen. >> E = input (Enter the Youngs modulus of Elasticity-) >>display(The calculated stresses are ) Also, fprintf can also be used instead of display command. >>frpintf(The engineering strains are ) 4.6 Controlling the appearance of floating point number By default, MATLAB displays only 4 decimals in the result of the calculations. But it can give the values up to 15 decimals of precision. The display is controlled by the command format. >>format short >>format short e >>format long e >>format short >>format bank 31.4162(4 decimal places) 3.1416e+01 3.141592653589793e+01 31.4162(4 decimal places) 31.42(2{decimal places) 1 (1 x 3 )

Also the command format compact suppresses any blank lines in the output, allowing more information to be displayed. 5. Plotting Tools The availability of several options in MATLAB makes plotting relatively easy, quick and convenient. Some of the useful options are tabulated below: 5.1. Basic plot commands Symbol plot (x,y) title ( ) xlabel/ylabel () text () gtext () grid on/off hold on/off axis([xmin xmax ymin ymax]) ginput plot3(x,y,z) linspace(a,b,n) Description Plots y vs. x Adds title on the top of the plot Attaches label to the x-axis/y-axis Adds text on the plot window Receives a text from mouse input Switches on/off the grid on the plot window Allows to add another plot to the current plot Scales x and y axes Produce a coordinate of a point on the plot screen Plots in 3D coordinate system Generates n+1 equispaced points between a and b, inclusive

Example: >>x = linspace(0,1,10); >>y1=sin(x); >>y2=cos(x); >>plot(x,y1) >>hold on >>plot(x,y2) >>title(Sine & Cosine Plots) >>xlabel(time) >>ylabel(y1&y2) >>grid on >>axis([0 11 -1.2 1.2])

The results are shown in the following figure:

5.2 Line Styles & Colors It is important to differentiate plots when we are drawing several plots on the same figure. Matlab provides various options to change the colors and line styles of the plots. By default, Matlab plots solid lines and colors in the order of blue, green and then red. However these can be controlled by adding a third argument in the plot command. For example, >> plot (x,y,g) uses a dashed green line for the plot The first character of the third argument specifies the color and the second, the line style. A list of options for various colors and line styles are provided below: Colors b blue g green r red y yellow c cyan m magneta w white k black Line styles . point o circle x x-mark + plus - solid -- dashed -. dash dot * star : dotted 9

5.3 Multi plots Several plots can be drawn in the same figure either by using the hold command as shown above or by using a single plot command. >> plot (x,y1,b-,x,y2,r) legend is another useful command in plotting multiple graphs on the same figure. >> legend (sine curve,cosine curve) Using these two commands instead of two plots command in the above example gives the following plot

10

S-ar putea să vă placă și