




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Professor: Quick; Class: Programming for Engineers with MATLAB; Subject: Computer Science; University: Penn State - Main Campus; Term: Fall 2009;
Typology: Study notes
1 / 8
This page cannot be seen from the preview
Don't miss anything!





2.3) Solving Problems with MATLAB: Variables: can be any length up to 63 characters, canât start with a number, no â-âs or other characters, try using underscores to separate words in a variable linspace(start, end, spacing) linspace(1,10,3) => 1 5.5 10 logspace(starting value of 10^x, end val of 10^x, # elements) logspace(1,3,3) => 10 100 1000 .* is used to perform element by element multiplication ./ is used to perform element by element division .^ is used to perform element by element exponentiation â is used at the end of a variable to transpose it Formats: format short = 4 decimal digits format long = 14 decimal digits format rat = fractional form 2.4) Saving Your Work: Dairy: allows you to record a MATLAB session save< file_name > ex: save my_function_file load< file_name > ex: load my_function_file
3.3) Elementary Math Functions sqrt(x) => takes the square root of variable x rem(x,y) => calculates the remainder of x divided by y size(x) => returns the size of the matrix x sin(x), cos(x), tan(x), etc⌠=> self-explanatory trig functions asin(x), acos(x), atan(x), etc⌠=> self-explanatory inverse trig functions exp(x) => computes the value of e^x log(x) => computes the value of ln(x) log10(x) => computes the value of log(x) abs(x) => finds the absolute value factorial(x) => computes the factorial of x floor(x) or ceil(x) => rounds x to the nearest integer factor(x) => finds the prime factors of x gcd(x,y) => finds the greatest common denominator of x and y same w lcm(x,y) prime(x) => finds all prime numbers less than x 3.5) Data Analysis Functions: max(x) => finds largest value in a vector, or largest in a column in a matrix min(x) => finds smallest value in a vector, or smallest in a column in a matrix mean(x), median(x), mode(x) => easy for a vector, in a matrix it does it for each row sum(x) => adds up all the elements in vector x or column in a matrix
prod(x) => computes product of all elements in a vector x or column of a matrix cumsum(x) => creates a vector the same size as x, adds up the values of x as it moves along the vector cumprod(x) => same as above except with multiplication sort(x) => sorts the elements of a vector x into ascending order sort(x, âdescendâ) => sorts the elements of a vector x into descending order sortrows(x) => to only sort the rows of a matrix length(x) => determines the length of a vector or largest dimension in a matrix std(x) => calculates the standard deviation of x var(x) => calculates the variance of the data in x rand(n) => returns a n x n matrix with numbers between 0 and 1 rand(m,n) => returns a m x n matrix with numbers between 0 and 1 randn(n) => returns a n x n matrix with numbers from -1 to 1 randn(m,n) => returns a m x n matrix with numbers from -1 to 1 complex(x, y) => returns x + yi ex: complex(3,5) = 3+5i
4.2) Problems With Two Variables: Meshgrid(x,y) => takes two inputs x and y. Then will create two two -dimensional matrices. Each of the resulting matrices has the same number of rows and columns. 4.3) Special Matrices: zeros(m) or zeros(m,n) => creates a matrix m x m or m x n filled with zeros ones(m) or ones(m,n) => creates a matrix m x m or m x n filled with ones diag(A) => extracts the diagonal of two-dimensional matrix A fliplr => flips a matrix into its mirror image from right to left flipud => flips a matrix vertically magic(m) => creates matrix m x m, all rows/columns add to same value
5.1) Two-Dimensional Plots: plot(x,y) => plots x versus y in a graphics window xlabel(âTime, secâ) => titles the x axis ylabel(âDistance, feetâ) => titles the y axis grid on => turns on the grid on the plot hold on or off => allows the user to put more than one plot on a graph plot(x,y, â:obâ) => changes the line to blue dashed and the points to circles or oâs axis([-2,3,0,10]) => fixes the axis of the plot of x to -2 to 3 and y to 0 to 10 legend(âstring1â, âstring2â,etcâŚ) => adds a legend to the graph 5.2) Subplots: subplot(m,n,p) => divides the graphics window into a grid of m by n; p is the subplot # 5.3) Other Types of Two-Dimensional Plots: polar(theta, r) => plots a polar graph semilogx(x,y) =>generates a plot of values x and y using a logarithmic scale for x only
\t tab \b backspace 7.3) Graphical Input: [x,y] = ginput => allows the user to select a point on the graph; stored in x & y 7.4) Using Cell Mode in MATLAB M-Files: Just simply put %% at the beginning of where youâd like your cell to start. 7.5) Reading and Writing Data From Files: Importing: doc filename, uiimport(âfilename.extensionâ), xlsread(âfilename.xlsâ) Exporting: xlxwrite(âfilename.xlsâ, M) M = array you wish to store into the spreadsheet
8.1) Relational and Logical Operators: Relational: < less than <= less than or equal to
greater than >= greater than or equal to == equal to ~= not equal to Logical: & and ~ not | or xor exclusive or 8.3) Logical Functions: find(variable >= number) this will search variable for a integer >= the number defined ex: [row, col] = find(temp>98.6) 8.4) Selection Structures: The Simple If: if comparison statements end The If/Else Structure: if comparison statements else statements end The Elseif Structure: if comparison if age< statements disp(âSorry, youâll have to waitâ) elseif comparison elseif age< statements disp(âYou can have a youth licenseâ) elseif comparison elseif age< statements disp(âYou can have a regular licenseâ) else else statements disp(âDrivers over 70 requireâŚâ) end end
The Switch and Case: switch variable case option code to be executed if variable is equal to option 1 case option code to be executed if variable is equal to option 2 otherwise code to be executed if variable is not equal to any options end Menu: input = menu(âMessage to userâ, âtext for button1â, âtext for button2â, etcâŚ) 8.5 Repetition Structures: Loops For Loops: for index = [matrix] for k = [1 3 7] commands to be executed k end end While Loops: k = 0 while criterion while k< commands to be executed k = k+ end end Break: this is used to terminate a loop prematurely Continue: similar to break, it just skips that command and goes to the next pass
9.1) Matrix operations and Functions: dot(A, B) => finds the dot product of matrix A and matrix B cross(A,B) => finds the cross product of matrix A and matrix B inv(A) => gets the inverse of matrix A det(A) => get the determinant of matrix A
10.1) Data Types: int8 - 8-bit signed integer uint8 - 8-bit unsigned integer int16 - 16-bit signed integer uint16 - 16-bit unsigned integer int32 - 32-bit signed integer uint32 - 32-bit unsigned integer 10.3) Character Arrays: Q = char(âHollyâ, âStevenâ, âMeaganâ, âDavidâ) will sort vertically R = [98;84;73;88;95;100] If we try to put these into one array, the values for R will correlate with the ASCII numbers for their represented keyboard values. If you want numbers to put next to the names, you must do S = num2str(R) then simply table = [Q,S] 10.4) Cell Arrays: Cell arrays can store different data types and sizes. Ex: my_cellarray = {A,B,C}
12.3) Using the Interactive Fitting Tools: To activate curve-fitting tools, generate a plot and then select Tools -> Basic Fitting. From there you can select what type of fitting you would like, linear, cubic, and show equations. You can also type in cftool to bring up the curve-fitting toolbox. 12.4) Differences And Numerical Differentiation: If all you have is your data and no equations relating it use this method. (ây/âx) = ((y 2 -y 1 )/(x 2 -x 1 )) to get âx: delta_x = diff(x); to get ây: delta_y = diff(y); slope = delta_y/delta_x; 12.5) Numerical Integration: This isnât the int function as used in Chapter 11, we are finding a bunch of rectangular areas under the curve and adding them together. To do this you must do the following: x = 0 : 0.1 : 1; y = x.^2; avg_y = y(1:10)+diff(y)/2; sum(diff(x).avg_y) -> ans = 0. Simpson Quadrature: MATLAB uses this: quad(âfuncâ, lower bound, upper bound) Lobatto Quadrature: MATLAB uses this: quadl(âfuncâ, lower bound, upper bound) 12.6) Solving Differential Equations Numerically: my_fun = @(t,y) 2t %corresponds to ((dy)/(dt)) = 2t [t,y] = ode45(my_fun, [-1,1], 1) %By graphing, the answer corresponds to t^
13.1) Images: advanced graphics are handled with image and imagesc functions. surf(peaks) => 3-D surface plot of the peaks function peaks is just in MATLAB pcolor(peaks) => 2-D surface plot of the peaks function shading flat => makes the grid lines disappear colormap(bone) => makes the image look like an x-ray colormap(jet) => the default coloring for an image imfinfo(âimage.jpgâ) => returns a whole bunch of info about the image colormap(map) => made the mandrill image from grey to colors axis image => corrects the axis settings so the image isnât warped How to load an image and get a X value: make sure the image is in the MATLAB dir X = imread(âimage_name.jpgâ) %loads the image image(X) %displays the image in a plot axis image %fixes axes so image isnât warped axis off %turns off axis so the image is the only thing displayed
13.2) Handle Graphics: Plot Handles: assigning a plot name (known as handle) allows us to easily ask MATLAB to list the plotted objectâs properties. Ex: x = 1:10; y = x.*1.5; h = plot(x,y) Variable h is the handle for the plot. To get the properties simply do get(handle_name) Figure Handles: f_handle = figure(1) get(f_handle) The only thing that differentiates figure handles and plot handles is the color property. If we donât specify a function handle, we can just do get(gfc) What We Use Handles For: to change colors and names/titles set(image_handle, âcolorâ, âredâ) OR set(image_handle, ânameâ, âTitleâ) 13.3) Animation: There are two techniques to creating animations: 1. Redrawing and erasing