BME 203 - MATLAB Midterm

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

placeholders

%d: integer notation %f: fixed point (decimal) notation (Most commonly used placeholder) %e: exponential notation %g: whichever is shorter, %f or %e. (Note: insignificant zeros do not print with %g) %c: character information %s: string of characters

logical operators

& is and ~ is not | is or

array operations

*, /, and ^ are used for matrix multiplication, division, and exponentiation only; .*, ./, and .^ are used for array multiplication, division, and exponentiation (element-by-element operations)

plot line styles

- = solid line (default) -- = dashed line : = dotted line -. = dash-dot line

E = zeros(3,5)

00000 00000 00000

hierarchy of operations

1.Parentheses () 2.Exponentiation (.^) 3.NOT operator (~) 4.Multiplication (.*) and division (./) 5.Addition (+) and subtraction (-) 6.Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), and not equal to (~=) 7.AND operator (&) 8.OR operator (|)

relational operators

< is less than > is greater than == is equal to <= is less than or equal to >= is greater than or equal to ~= is not equal to

fractional relative error

= (absolute error/true value) * 100%; gives an indication of how good the approximation is relative to the true value

absolute error

= true value - approximation; shortcoming (an error of micrometers can be significant for the size of a cell for example)

indexing into an array

A = [2,1,3] A(1,2) = 5, so then A = [2,5,3] can also extend with A(1,6) = 8, so then A = [2,5,3,0,0,8]

colon notation vs. linspace

CN: first value:final value or first:increment:limit ex. H = 1:6 makes H = 1 2 3 4 5 6 and I = 1:3:21 makes I = 1 4 7 10 13 16 19 LS: linspace(X1,X2,N) ex. linspace(1,10,10) makes 1 2 3 4 5 6 7 8 9 10 linspace (1,20,10) makes 1.00 3.11 5.22 7.33 9.44 11.56 13.67 15.78 17.89 20

extracting data using the colon operator

G = [1,2,3;4,5,6;7,8,9] 123 456 789 to extract second row you do J = G(2,:), so J = 4 5 6 to extract the first column you do K = G(:,1), so K = 1 4 7 to extract the second and third rows you do L = G(2:3,:), so L = 456 789 to extract the second and third columns of the first row you do M = G(1,2:3), so M = 2 3

surface mesh plots

[X, Y] = meshgrid(x, y); Z = f (X, Y); mesh (X, Y, Z) or surf (X, Y, Z)

formatting commands

\n = linefeed \r = carriage return \t = tab

variance

a measure of how data points differ from the mean (mean, median, mode,range)

standard deviation

a measure of variation of scores about the mean; population and sample; we usually use sample standard deviation, which is denoted std( )

arithmetic operations

addition a + b subtraction a - b multiplication a .* b division a ./ b exponentiation a .^ b

for loops

allow a sequence of MATLAB statements to be executed more than once; for loops repeat a block of commands for a specified matrix which is known before the loop is executed structure: for index = [index matrix] command #1 command #2 command #3 . . . end ex. clear all, close all for a = [1,8,4,5] disp(a) end >>a a = 5 (because this is the last value in the index after the final time through the loop) ex. for n = 1:5 fprintf(' The value of n is now %d\n', n); end The value of n is now 1 The value of n is now 2 The value of n is now 3 The value of n is now 4 The value of n is now 5 >> ex. clear all; close all for x = [pi/7, pi/5, pi/3] disp([x,sin(x)]) end 0.4488 0.4339 0.6283 0.5878 1.0472 0.8660 >>

fprintf

allows you to print data and array values ex. A1 = [9.9, 9900]; A2 = [8.8, 7.7 ; ...8800, 7700]; formatSpec = 'X is %4.2f meters or %8.3f mm\n'; fprintf(formatSpec,A1,A2) Gives X is 9.90 meters or 9900.000 mm X is 8.80 meters or 8800.000 mm X is 7.70 meters or 7700.000 mm ex. radius = input('Enter the radius: '); area = pi .* radius .^ 2; fprintf('The area of the circle is %f.', area);

nested while loops

as with for loops, we can nest if statements and other loops in a while loop ex. clear all;close all stress = [4.2 3.8 6.7 2.3 8.9 1.6 6.4]; count = 0; i=0; while i<length(stress) % outer while loop i=i+1; if stress(i)<=4.0 % inner if statement count=count+1; end % end if statement end % end while loop fprintf('Number osteoporotic bones: %d\n',count) Number osteoporotic bones:3

=

assignment operator (not "equals"); equals is == (2 equal signs)

functions with no input or output

can be used for a procedure ex. tic toc to time things

functions with no output

can be used in plot figures ex. title(' ') to title a plot

cnew

cnew = poly(r) used to get the polynomial when you know the roots

concatenation

combining matrices (defined under a new matrix) ex. A = [ 12, 18, -3] B = [2, 5, 2 ; 1, 1, 2 ; 0 -2 6] then new matrix C = [A; B] which is C = [ 12, 18, -3; 2, 5, 2 ; 1, 1, 2 ; 0, -2, 6] can also do D = [C, C] as long as the matrices have the same boundaries (3x4 with a 3x4, 2x2 with a 2x2, etc.)

round-off errors

computing device is unable to deal with inexact numbers, so these numbers need to be rounded off to some near approximation which is dependent on the space allotted by the device to represent the number

contour plots

contour(image, #) colormaps: parula jet hsv hot cool spring summer autumn winter grey bone coppur pink lines

fzero( )

designed to find the real root of a single equation using a combination of bisection, secant, and inverse quadratic interpolation methods

if/else

else clause allows you to execute one set of statements if the condition is true and a different set of statements if the condition is false structure: if condition actions else actions end other actions ex. function numCheck(x) if isnumeric(x) fprintf('Input is numeric array \n') else fprintf('Error: input is not a numeric array \n') end

elseif function

elseif clause allows you to check multiple criteria while keeping code easy to read; the first elseif argument that is true will be executed (the program will then go to the end statement) structure: if condition1 actions elseif condition2 actions else actions end other actions ex. function letter=grades(num) if num >= 90 letter='A or A-' elseif num >= 75 letter='B-, B or B+' elseif num >= 60 letter='C-, C or C+' elseif num >= 50 letter='D' else letter='F' end

truncation errors

errors in a method, which occur because some series (finite or infinite) is truncated to a fewer number of terms

riemann sum

estimates graph based on rectangles ex. delta_x=1:-0.0001:0; integral=0; i=1; while abs(integral-0.6593)>1E-4 x=1; integral=0; while x<=2; integral=integral + (sin(x)/x)*delta_x(i) x = x + delta_x(i); end i=i+1; end

simple logical programming

ex. A = [1 2 3 4 0 5 6] A~=0 ans = 1 1 1 1 0 1 1 (tells you which values in A are not zero) A(A~=0); A A = 1 2 3 4 5 6 (tells you the values of A which are not zero)

converting for to while loop

ex. FOR LOOP for index = [index matrix] commands end WHILE LOOP index = [index matrix] while i<length(index) commands i=i+1 end

converting while to for loops

ex. WHILE LOOP while logical expression commands end FOR LOOP for index = [data set] if logical expression break; end commands end

for loops with vectors and matrices

ex. for n=1:5 fprintf('The value of n is now %d\n', n); vector_1(n) = n vector_2(n) = n^2; end Vector_1 stores the value of n vector_1 = [1 2 3 4 5] Vector_2 stores the square of n vector_2 = [1 4 9 16 25]

nested if statement

ex. function numericprime(num) if isnumeric(num) fprintf('Numeric input \n') if isprime(num) fprintf('Prime number \n') else fprintf('Input not prime \n') end else fprintf('Error: Not numeric \n') end

for loops - data analysis

ex. subplot(1,2,1); R=randn(100,100); imagesc(R); colormap hot; axis square colorbar; for i=1:100; for j=1:100; if R(i,j) < 0; R(i,j)=0; else; end end end subplot(1,2,2); imagesc(R); axis square; colorbar;

polar plots

ex. theta = 0:0.01:pi; r=sin(theta); subplot(2,1,1) plot(theta, r); axis square subplot(2,1,2) polar(theta, r)

exponential plots

exponential growth y = Ce^kt, k>0 exponential decay (decreasing form) y = Ce^-kt, k>0 exponential decay (increasing form) y = C(1-e^-kt), k>0

gaussian distribution

f(x) = gaussmf(x, [std mu]) -std is the standard deviation -mu is the mean -x is the parameter under scrutiny ex. [X Y] = hist(height,9); axis square; X = X/sum(X)% Bin fraction bar(Y,X)% Creates a bar plot hold on A = mean(height) % 173.4926 C = std(height) % 10.43 y = max(X)*gaussmf(x,[C A]) xlim([130,210]) title('Class height [cm]','Fontsize',22) plot(x,y,'r') ex. x = -100:1:1200 y1 = gaussmf(x, [50, 100]); y2 = gaussmf(x, [100, 300]); y3 = gaussmf(x, [150, 500]); y4 = gaussmf(x, [200, 700]); plot(x,y1,'r'); hold on plot(x,y2,'b') plot(x,y3,'k') plot(x,y4,'g') xlim([-100 1200])

find function

find( ) to search an array to identify the index values of specific elements in the array ex. x=[1,8,6,3,2,4,9,0,5,7] IndexValues=find(x>5) X(IndexValues) >> ans=8 6 9 7

fplot

fplot(function,[xmin xmax]) fplot(function,xmin xmax ymin ymax)

width and precision field

fprintf('%8.3f\n', 3.3333) width field (8) specifies the minimum number of characters to be printed (if the number is shorter than the number of characters, it will be padded with spaces) in this case 3 spaces will be added to use 8 characters precision field (.3) specifies the number of digits to be printed to the right of the decimal point (if there are more digits to be printed after the decimal than space provided, fprintf( ) will round the number using the same rules as round( )

function with multiple inputs and outputs

function [xx,yy,zz] = sphere2cart(r,theta,phi) zz = r.*cosd(theta); xx = r.*sind(theta).*cosd(phi); yy = r.*sind(theta).*sind(phi); ex. clear,clc xy_ang = [0:1:90]; xyp_z_ang = [0:1:90]; radius=10:1:100; [x,y,z]=sphere2cart(radius, xy_ang, xyp_z_ang); row_results=[x;y;z] column_results=[x',y',z']

functions with no input

function mass_of_earth = moe() mass_of_earth = 5.976E24;

trapz( )

function to get trapezoidal riemann sum ex. X = 1:1/15:2; Y = sin(X)./X; Z = trapz(X,Y) Z=0.6593

plotting commands

grid on/grid off title('Title here') xlabel('x label') xlabel('x label','Fontsize',30) ylabel('y label') Legend('First','Second','Third','Location','NorthEast') semilogx(x,y)/semiology(x,y)/loglog(x,y) set(gca,'Fontsize',32) - modifying axes figure( ) - useful for multiple plots axis([xmin,xmax,ymin,ymax]) - useful for axis scaling text(2,90,'add text') - adding text

infinite loop

i=20 while i<50 fprintf('Count is now %d.\n',i) i=i-1 end

if statement

if statements allow you to execute a series of statements if a condition is true and to skip the stops if the condition is false basic if statement has the form: if condition actions end other actions ex with arrays. g = 0:10:80; if g < 50 fprintf('g is less than 50. \ n'); end (some elements of g are greater than 50, so the statement is false, and therefore there is no output

xlsread( ) and xlswrite( )

importing and exporting excel data

logarithmic plots

logarithmic growth y = a + bln(t) logarithmic growth model y = a/(1+be^-kt), k>0

trapezoidal method

more accurate riemann sum ex. delta_x=1:-0.0001:0; integral=0; i=1; while abs(integral-0.6593)>1E-4 x=1; integral=0; while x<=2; integral = integral + 0.5*delta_x(i)*((sin(x)/x)+(sin(x+delta_x(i))/(x+delta_x(i)))); x = x + delta_x(i); end i=i+1; end i

plot marker symbols

o = circle + = plus sign * = asterisk . = point x = cross s = square d = diamond ^ = upward-pointing triangle v = downward-pointing triangle > = right-pointing triangle < = left-pointing triangle p = pentagram h = hexagram

nested loops

one loop that is written inside another loop (inner loop is the nested loop) ex. clear all,close all r = 1:1:100 c = 1:1:200 A=[ ] % This creates an empty array (see preallocation) for i=1:length(c) %outer for loop for j = 1:length(r) % inner (nested) loop if i >= 90 & i<=110 & j > 40 & j <= 65 A(i,j) = 1; else A(i,j) = 0; end end end imagesc(A);colormap gray

3d plots

plot3(x,y,z) ex. t = 0:pi/50:10*pi; st = sin(t); ct = cos(t); plot3(st,ct,t,'LineWidth',3)

polyfit( ) function

polyfit(x,y,n) takes x data, y data, and degree n of a polynomial function returns the coefficients of the polynomial that best fits the data

polyval( ) function

polyval(coefficients,data) outputs/calculates the fitted data

root function

roots( ) used to calculate roots of polynomials x = roots(c) where x is a column vector containing the roots and c is a row vector containing the polynomials

matrix row/column

rows come first, then column (for example, when finding a value, m(2,3) is in the second row and third column); rows are separated by semicolons and columns are separated by colons

saving variables

save filename var1 var2 var3 ... - saves the variables load filename - loads variables

logarithmic plots

semilogx,semilogy,loglog

sin vs sind

sin of something in radians vs. sin of something in degrees

subplot

subplot(m,n,p) where m is rows, n is columns, and p is the window where the plot would be drawn

transpose operator

switches the array from a row to a column or a column to a row ex. N = [1,3,7] O = N' O = 1 3 7

flowcharts

symbols: oval = indicate beginning/end of a section of code, parallelogram = indicate input or output processes, diamond = indicates a decision point, rectangles = calculations are placed in rectangles

is function

test if something is true/false ex. function is true when... ischar( ) = input is character array isfinite( ) = input is finite isinf( ) = input is infinite isletter( ) = input is alphabetic letter isnumeric( ) = input is numeric array

logic

true is (1) false is (0)

view the path

type pathtool

break

used to terminate loop permanently (when the expression in the first line is still true); causes termination of the smallest enclosing loop ex. sum=0 fprintf('Input positive numbers.\n'); fprintf('Enter a negative number to quit.\n'); num=input('Enter Number: '); while num>=0 if isinf(num) break; end sum=sum+num; num=input('Enter next number: '); end fprintf('The sum of the numbers is: %f.\n', sum);

tic and toc/timing loops

used to time the code; timing loops sees how many random numbers you can write in 20 seconds ex. i=1; tic while toc < 20 num(i)=rand(1,1); i=i+1; end i

while loops

useful for repeating a procedure an unknown number of times as long as a certain statement is true; can be used to acquire data in experiments; useful when a procedure needs to be repeated until a specific criterion is met; repeats as long as an expression is true (1), stops when the expression is false (0) structure: while expression command #1 command #2 command #3 . . . end ex. clear all;close all total = 0 i=1; num(i)=input('Input number to sum\n(to exit enter negative number):') while num(i)>=0 & ~isinf(num(i)) total=total+num(i) i=i+1; num(i)=input('Input number to sum\n(to exit enter negative number):') end fprintf('The total of the numbers you input was %f.\n',total)

pseudocode

verbal description of your plan for writing a program, can be combo of English and MATLAB code or just Enlgish (but not just MATLAB code); typically ends up as your commented lines of code, next to the actual code ex. % Define a vector of mm Hg values % Convert mm HG into Pa % Combine the mm Hg and Pa vectors into a matrix % Create a table title % Display column headings using fprintf() % Display the table using fprintf()

bar graphs

x = [1,3,8,5,4,6]; bar(x) for vertical bar graph and barh(x) for horizontal bar graph

pie charts

x = [1,3,8,5,4,6]; figure(1) pie(x)

Gaussian

y = ae^(-(x-c)^2)/(b^2)

plot colors

y = yellow m = magenta c = cyan r = red g = green b = blue w = white k = black


संबंधित स्टडी सेट्स

Le Corbusier & Frank Lloyd Wright

View Set

General Biology I - Chapter 8: Photosynthesis

View Set

Pharmacy Law Practice Exam Questions

View Set

Elsevier adaptive quizzing ENDOCRINE system

View Set

CHPTR 9 Inflammation, Davis. Adv. Assessments w/ Pre & Post

View Set

151 MT2 - Dissonance & Justification

View Set