Programming for Engineers with MATLAB - Study Guide | CMPSC 200, Study notes of Computer Science

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

Pre 2010

Uploaded on 05/03/2010

cdt5058
cdt5058 🇺🇸

2 documents

1 / 8

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 2 – MATLAB Environment
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
Chapter 3 – Built In MATLAB Functions
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
pf3
pf4
pf5
pf8

Partial preview of the text

Download Programming for Engineers with MATLAB - Study Guide | CMPSC 200 and more Study notes Computer Science in PDF only on Docsity!

Chapter 2 – MATLAB Environment

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

Chapter 3 – Built In MATLAB Functions

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

Chapter 4 – Manipulating MATLAB Matrices

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

Chapter 5 – Plotting

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

Chapter 8 – Logical Functions and Control Structures

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

Chapter 9 – Matrix Algebra

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

Chapter 10 – Other Kinds of Arrays

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^

Chapter 13 – Advanced Graphics

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

  1. Creating a movie Redrawing and Erasing: In order to do this option, you need to first create a plot then adjust the properties of the graph each time through a loop. EX: x = -10 : 0.1 : 10; k = -1; y = kx.^2-2; h = plot(x,y) grid on axis([-10,10,-100,100]) %Specifies the axis while k<1 %Start a loop k = k+0.01; %Increment k y = kx.^2-2 %Recalculate y set(h, ‘XData’, x, ‘YData’, y) %Reassigns the x and y values used in the graph drawnow %Redraws the graph now – doesn’t wait until program is done end Movies: Movies are used typically for surface plots, it’ll run through the computation stuff once (might be a little jerky due to computations), then play through the whole set of frames twice. Transparency: Set by the function alpha(decimal 0 to 1)