Curs 0 Introducere in Matlab

73
MATLAB MATLAB Matrix Matrix Laboratory Laboratory La disciplina METALIMBAJE

description

matlab

Transcript of Curs 0 Introducere in Matlab

  • MATLABMatrix LaboratoryLa disciplina METALIMBAJE

  • Student Edition MATLAB Similar cu Versiunea ProfesionalaAbilitate de a apela rutine C, C++ si FortranMatrice pana la 16,384 (128 x 128) elementeTrei toolbox-uri: Procesare Simnal, Sisteme de Control si Mat. Simbolica

  • Metodologia de rezolvare a problemei Formularea clara a problemeiDescriere informatiilor intrare si iesire (I/O)Se lucreaza problema cu mana pentru un caz simplu Se stabileste algoritmul de aplicare a metodei numericeSe dezvolta solutia MATLABSe depaneaza si se testeazaSe intocmeste documentatia

  • MATLAB ReviewMATLAB is a numerical analysis systemCan write programs, but they are not compiledShould still use structured programmingShould still use commentsComments are indicated by % at the beginning of the line

  • Program DocumentationYou must include comments in the computer programs you turn in -- otherwise we will have great difficulty knowing what you are doingComments!!!

  • For example, here is some cryptic code without commentfor j=0:2k=(2-j)*(1+3*j)/2endWhat does it do? Put a comment in% turns (0,1,2) into (1,2,0)

  • MATLAB WindowsCommand Window -- enter commands and data -- print results Graphics Window -- display plots and graphsEdit Window -- create and modify m-files

  • Managing MATLAB Environmentwho or whos -- See the current runtime environmentclear -- remove all variables from memoryclc -- clear the command windowclf -- clear the graphics windowsave -- save the workspace environmentload -- restore workspace from a disk fileabort -- CTRL-Chelp -- help commandReally good help command

  • MATLAB SyntaxNo complicated rulesPerhaps the most important thing to remember is semicolons (;) at the end of a line suppress outputType more on to keep text from leaving screen too fastdiary filename saves a text record of sessiondiary off turns it off

  • MATLABMATLABs basic component is a Vector or Matrix Even single value variables (Scalars)All operations are optimized for vector useLoops run slower in MATLAB than in Fortran (not a vector operation)size command gives size of the matrix

  • Scalars, Vectors, MatricesMATLAB treat variables as matricesMatrix (m n) - a set of numbers arranged in rows (m) and columns (n)Scalar: 1 1 matrixRow Vector: 1 n matrixColumn Vector: m 1 matrix

  • >> pians = 3.1416

    >> size(pi)ans = 1 1

    >> a=[1 2 3; 4 5 6]a = 1 2 3 4 5 6

    >> size(a)ans = 2 3a=

  • x=3+5-0.2x = 7.8000 y=3*x^2+5y = 187.5200 z=x*sqrt(y)z = 106.8116 A=[1 2 3; 4 5 6]A = 1 2 3 4 5 6 b=[3;2;5]b = 3 2 5 C=A*bC = 22 52 who

    Your variables are:

    A b y C x z

    whos Name Size Bytes Class

    A 2x3 48 double array C 2x1 16 double array b 3x1 24 double array x 1x1 8 double array y 1x1 8 double array z 1x1 8 double array

    save

    Saving to: matlab.mat

    save matrix1MATLAB Exampledefault filenamefilename matrix1

  • Data typesAll numbers are double precisionText is stored as arrays of charactersYou dont have to declare the type of data (defined when running)MATLAB is case-sensitive!!!Laura ; LAURA; LAura

  • Variable NamesUsually, the name is identified with the problem Variable names may consist of up to 31 charactersVariable names may be alphabetic, digits, and the underscore character ( _ )Variable names must start with a letterABC, A1, C56, CVEN_302day, year, iteration, maxtime, velocity, distance, area, density, pressure Time, TIME, time (case sensitive!!)

  • Initializing VariablesExplicitly list the valuesreads from a data fileuses the colon (:) operatorreads from the keyboardA = [1; 3; 5; 10]; B = [1 3 5; -6 4 -1]C = [2 3 5 1; 0 1 (continuation) 1 -2; 3 5 1 -3]E = [A; 1; A]; F = [C(2,3); A]

  • Matrix Concatenation

  • Colon OperatorCreating new matrices from an existing matrixC = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]F = C(:, 2:3) = [2,5; 0,1; 2,-1; 1,4]

  • Colon OperatorCreating new matrices from an existing matrixC = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]E = C(2:3,:) = [-1 0 1; 3 2 -1]

  • Colon OperatorCreating new matrices from an existing matrixC = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]G = C(3:4,1:2) = [3,2; 0,1]

  • Colon OperatorVariable_name = a:step:b time = 0.0:0.5:2.5 time = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5] values = 10:-1:2 values = [10, 9, 8, 7, 6, 5, 4, 3, 2]

    linspace gives 100 evenly spaced valuesx = linspace(1,n)x = linspace(a,b,n_pts)

  • Special Matrices

  • Arithmetic Operations Between Two ScalarsExample: x = (a + b*c)/d^2 count = count + 1

  • Precedence of Arithmetic Operations1 Parentheses innermost first2 exponentiation, left to right3 multiplication and division, left to right4 addition and subtraction, left to right Examples: factor = 1 + b/v + c/v^2 slope = (y2 - y1)/(x2 - x1) loss = f * length/dia * (1/2 * rho * v^2) func = 1 + 0.5*(3*x^4 + (x + 2/x)^2)

  • Array OperationsAn array operation is performed element-by-elementMATLAB: C = A.*B;

  • Element-by-Element OperationsArray Operation

  • Vector and Matrix operationsBut a*b gives an error (undefined) because dimensions are incorrect. Need to use .*

  • Vectorized Matrix Operations

  • Array Operations for M N Matrices

  • Matrix Transpose

  • Data FilesMAT Files -- memory efficient binary format -- preferable for internal use by MATLAB program

    ASCII files -- in ASCII characters -- useful if the data is to be shared (imported or exported to other programs)

  • MATLAB Input To read files inif the file is an ascii table, use loadif the file is ascii but not a table, file I/O needs fopen and fcloseReading in data from file using fopen depends on type of data (binary or text)Default data type is binary

  • Save Files8-digit text format (variable list) save - ascii16-digit text format save - doubleDelimit elements with tabs save - double - tabsExample: Vel = [1 3 5; -6 2 -3] save velocity.dat Vel -ascii 1.0000000e+000 3.0000000e+000 5.0000000e+000 -6.0000000e+000 2.0000000e+000 -3.0000000e+000

  • Load FilesRead velocity into a matrix velocity.dat >> load velocity.dat >> velocity velocity = 1 3 5 -6 2 -3 1.0000000e+000 3.0000000e+000 5.0000000e+000 -6.0000000e+000 2.0000000e+000 -3.0000000e+000

  • Load FilesCreate an ASCII file temp.dat

    read Time and Temperature from temp.dat >> load temp.dat >> temp % Time Temperature 0.0 75.0 0.5 73.2 1.0 72.6 1.5 74.8 2.0 79.3 2.5 83.2

  • MATLAB OutputMatlab automatically prints the results of any calculation (unless suppressed by semicolon ;)Use disp to print out text to screen disp (x.*y) disp (Temperature =)sprintf - display combinationMake a string to print to the screenoutput = sprintf(Pi is equal to %f , pi)

  • Formatted Outputfprintf (format-string, var, .)%[flags] [width] [.precision] typeExamples of type fields%e display in exponential notation%f display in fixed point or decimal notation%g display using %e or %f, depending on which is shorter%% display %

  • Numeric Display Formatx = [5 -2 3 0 1 -2]; format +x = [+ - + + -] (+/- sign only)

  • fprintf( ) of Scalartemp = 98.6;fprintf(The temperature is %8.1f degrees F.\n, temp);The temperature is 98.6 degrees F.fprintf(The temperature is %8.3e degrees F.\n, temp);The temperature is 9.860e+001 degrees F.fprintf(The temperature is %08.2f degrees F.\n, temp);The temperature is 00098.60 degrees F.

  • fprintf( ) of MatricesScore = [1 2 3 4; 75 88 102 93; 99 84 95 105]

    Game 1 score: Houston: 75 Dallas: 99Game 2 score: Houston: 88 Dallas: 84Game 3 score: Houston: 102 Dallas: 95Game 4 score: Houston: 93 Dallas: 105 fprintf(Game %1.0f score: Houston: %3.0f Dallas: %3.0f \n,Score)

  • Built-in FunctionsAll the standard operators +, -, *, /, ^sin( ), cos( ), exp( ), tanh( ), log( ), log10( ), etc.These operators are vectorized

  • Common Program StructuresSequenceSelectionRepetition

  • Selection (if) StatementsThe most common form of selection structure is simple if statementThe if statement will have a condition associated with itThe condition is typically a logical expression that must be evaluated as either true or falseThe outcome of the evaluation will determine the next step performed

  • Logical IF StatementsIf (condition) executable_statements end -11x1y if (x < = -1.0 | x > = 1.0) y = 0.endif (x > -1.0 & x < 0.) y = 1. + xendif (x > = 0. & x < 1.0) y = 1.- xend

  • Relation Operators MATLAB == ~= < >= & | ~Interpretationis equal tois not equal tois less thanis less than or equal tois greater thanis greater than or equal toand, true if both are trueor, true if either one is truenot

  • Logical Operators 0 - 1 matrix0: false ; 1: True

  • Nested IF Statementif (condition) statement blockelseif (condition) another statement blockelse another statement blockend

  • How to use Nested IFIf the condition is true the statements following the statement block are executed.If the condition is not true, then the control is transferred to the next else, elseif, or end statement at the same if level.

  • Else and Elseifif temperature > 100 disp(Too hot - equipment malfunctioning.)elseif temperature > 75 disp(Normal operating range.)elseif temperature > 60 disp(Temperature below desired operating range.)else disp(Too Cold - turn off equipment.)end

  • Nested IF Statementsnested if (if, if else, if elseif) -11x1y if (x < = -1.0) y = 0.elseif (x < = 0.) y = 1. + xelseif (x < = 1.0) y = 1. - xelse y=0.end

  • Do loopsRepetition

    for i=1:mfor j=1:na(i,j)=(i+1)^2*sin(0.2*j*pi);endendUse script file for all do loops

  • For Loopsfor index = expression statements endfor k = 1:length(d) if d(k) < 30 velocity(k) = 0.5 - 0.3*d(k).^2; else velocity(k) = 0.6 + 0.2*d(k)-0.01*d(k).^2 endend

  • While Loops

    while index = expression statements endIf the statement is true, the statements are executedIf the statement is always true, the loop becomes an infinite loopThe break statement can be used to terminate the while or for loop prematurely.

  • MATLAB GraphicsOne of the best things about MATLAB is interactive graphicsplot is the one you will be using most oftenMany other 3D plotting functions -- plot3, mesh, surfc, etc.Use help plot for plotting optionsTo get a new figure, use figurelogarithmic plots available using semilogx, semilogy and loglog

  • Plotting Commandsplot(x,y) defaults to a blue lineplot(x,y,ro) uses red circlesplot(x,y,m*) uses magenta asterisksIf you want to put two plots on the same graph, use hold onplot(a,b,r:) (red dotted line)hold onplot(a,c,ko) (black circles)

  • x=0:0.1:5; y=2*x.^3-12*x.^2+8*x-6; H=plot(x,y,'b',x,y,'r*'); set(H,'LineWidth',3,'MarkerSize',12) xlabel('x'); ylabel('y'); title('f(x)=2x^3-12x^2+8x-6'); print -djpeg075 poly.jpgelement-by-element operations x.^n

  • x=0:0.1:10; y=sin(2.*pi*x)+cos(pi*x); H1=plot(x,y,'m'); set(H1,'LineWidth',3); hold on; H2=plot(x,y,'bO'); set(H2,'LineWidth',3,'MarkerSize',10); hold off; xlabel('x'); ylabel('y'); title('y = sin(2*pi*x)+cos(pi*x)'); print -djpeg075 function.jpg

  • x=0:0.1:3; y1=exp(-x); y2=sqrt(x); H=plot(x,y1,'b-',x,y2,'r--'); set(H,'LineWidth',3) xlabel('x'); ylabel('y'); title('MATLAB Plots'); H1=text(1.8,0.2,'exp(-x)'); set(H1,'FontSize',18); H2=text(1.8,1.3,'sqrt(x)'); set(H2,'FontSize',18);

  • M-Files: Scripts and FunctionsYou can create and save code in text files using MATLAB Editor/Debugger or other text editors (called m-files since the ending must be .m) M-file is an ASCII text file similar to FORTRAN or C source codes ( computer programs)A script can be executed by typing the file name, or using the run commandDifference between scripts and functionsScripts share variables with the main workspaceFunctions do not

  • Plotting Commandsplot (x, y)plot(x1, y1, x2, y2)plot (x, y, color symbol line style) x = linspace(0, 2*pi); y = sin (2.*x); z = cos (0.5*x); plot (x, y) plot (x, y, x, z) figure (2) plot (x, y, 'r o -'); grid on hold on plot (x, z, 'b * :')(red, circle, solid line)(blue, star, dotted line)figure or figure (#) : open a figure

  • Graphics CommandsAxis, Labels, and Title xlabel (Time) ylabel (Temperature) title (Temperature Record : 1900 - 2000) text (17, 120, Record High ) text (85, -40, Record Low ) axis ([0 100 -50 140]) hold offxlabel ( label )ylabel ( label ) title ( title of the plot ) text ( x_location, y_location, text ) axis ( [ x_min x_max y_min y_max ] ) - text string

  • MATLAB ExampleFilename waves.m (script file)% Plot Bi-chromatic Wave Profilea1 = 1; a2 = 1.5; c1 = 2.0; c2 = 1.8;time = 0:0.1:100;wave1 = a1 * sin(c1*time);wave2 = a2 * sin(c2*time) + a1;wave3 = wave1 + wave2;plot(time,wave1,time,wave2,time,wave3)axis([0 100 -2 4]);xlabel ('time'); ylabel ('wave elevation');title ('Bi-chromatic Wave Profile')text(42,-1.2, 'wave 1')text(42, 2.7, 'wave 2')text(59, 3.6, 'waves 1+2')

  • MATLAB SubplotsFilename waves2.m (script file)% Plot Bi-chromatic Wave Profile% Display the results in three subplotsclf % clear the graphics windowa1 = 1; a2 = 1.5; c1 = 2.0; c2 = 1.8;time = 0:0.1:100;wave1 = a1 * sin(c1*time);wave2 = a2 * sin(c2*time);wave3 = wave1 + wave2;subplot(3,1,1) % top figureplot(time,wave1,'m'); axis([0 100 -3 3]); ylabel('wave 1');subplot(3,1,2) % middle figureplot(time,wave2,'g'); axis([0 100 -3 3]); ylabel('wave 2');subplot(3,1,3) % bottom figureplot(time,wave3,'r'); axis([0 100 -3 3]);xlabel(time'); ylabel('waves 1&2');

  • MATLAB Subplotssubplot ( m, n, p ) -- breaks the figure window into m by n small figures, select the p-th figure for the current plot figure (3) subplot (3, 2, 1) plot (t,wv1) subplot (3, 2, 2) plot (t,wv2) subplot (3, 2, 4) plot (t, wv1+wv2) subplot (3, 2, 6) plot (t, wv1-wv2)123456

  • x=0:0.1:10; y1=sin(pi*x); y2=sin(0.5*pi*x); y3=y1+y2; z1=cos(pi*x); z2=cos(0.5*pi*x); z3=z1-z2; subplot(3,2,1); H1=plot(x,y1,'b'); set(H1,'LineWidth',2); subplot(3,2,2); H2=plot(x,z1,'b'); set(H2,'LineWidth',2); subplot(3,2,3); H3=plot(x,y2,'m'); set(H3,'LineWidth',2); subplot(3,2,4); H4=plot(x,z2,'m'); set(H4,'LineWidth',2); subplot(3,2,5); H5=plot(x,y3,'r'); set(H5,'LineWidth',2); subplot(3,2,6); H6=plot(x,z3,'r'); set(H6,'LineWidth',2);Subplot (m,n,p)Multiple plots

  • Script File for Integral1. Save integral (f, a, b) in script file integral.m2. Save function my_func(x) in script my_func.m3. Run script file >> area = integral(my_func, 1, 10) >> area = integral(my_func, 3, 6)areaabf(x)x

  • FunctionsOne variable function y = function_name(input arguments)More than one output variables function [y, z] = function_name(input arguments)Examples: function y = my_func (x) y = x^3 + 3*x^2 -5 * x +2 ;

    function area = integral (f, a, b) ya = feval (f, a); yb = feval(f, b); area = (b-a)*(ya+yb)/2;

  • feval - evaluate function specified by stringfunction y = my_func(x)% function 1/x^3y = x.^(-3);function q = basic_trap(f, a, b)% basic trapezoid rule ya = feval(f, a);yb = feval(f, b);q = (b - a)* (ya + yb)/2;my_func.mbasic_trap.m y = basic_trap ('my_func', 1,3)y = 1.0370

  • function t = trap_ex(a, b)t = (b - a) * (a^(-3) + b^(-3)) / 2;Approximate the integral of f(x) = 1/x3 using basic trapezoid ruleFilename: trap_ex.m y = trap_ex (1, 3)y = 1.0370

  • Composite Trapezoid Rulefunction I = Trap(f, a, b, n)% find the integral of f using % composite trapezoid ruleh=(b - a)/n; S = feval(f, a);for i = 1 : n-1 x(i) = a + h*i; S = S + 2*feval(f, x(i));endS = S + feval(f, b); I =h*S/2;Filename: comp_trap.m xfab

  • Composite Trapezoid Rule I=comp_trap('my_func',1,3,1)I = 1.0370 I=comp_trap('my_func',1,3,2)I = 0.6435 I=comp_trap('my_func',1,3,4)I = 0.5019 I=comp_trap('my_func',1,3,8)I = 0.4596 I=comp_trap('my_func',1,3,16)I = 0.4483 I=comp_trap('my_func',1,3,100)I = 0.4445 I=comp_trap('my_func',1,3,500)I = 0.4444 I=comp_trap('my_func',1,3,1000)I = 0.4444one segmenttwo segmentsfour segmentseight segments16 segments100 segments500 segments1000 segments

    H.C. Chen MATLAB Review H.C. Chen MATLAB Review