Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to MATLAB® Dr M Ali Ahmadi-Pajouh KN Toosi University.

Similar presentations


Presentation on theme: "An Introduction to MATLAB® Dr M Ali Ahmadi-Pajouh KN Toosi University."— Presentation transcript:

1 An Introduction to MATLAB® Dr M Ali Ahmadi-Pajouh KN Toosi University

2 MATLAB= Matrix + Laboratory Usage : –Math and computation Algorithm – development Data acquisition Modeling simulation, and prototyping –Data analysis exploration, and visualization –Scientific and engineering graphics –Application development, including graphical user interface building –…

3 Development Environment

4 Desktop Tools Command Window

5 Desktop Tools Start = easy access to tools, demos, and documentation.

6 Current Directory Browser file you want to run must either be in the current directory or on the search path

7 Workspace Browser

8 Editor/Debugger M-files are programs you write to run MATLAB functions.

9 Matrix To enter a matrix, simply type in the Command Window: A = [ ; ; ; ] MATLAB displays the matrix you just entered. A =

10 Transpose So A' produces ans = A =

11 Diagonal Elements diag(A) produces ans = A =

12 Assigning a new Value to an Element X(4,4) = 17 X = A =

13 Storing an Element >>t = A(4,3) t= 14 A =

14 The Colon Operator The expression 1:10 is a row vector containing the integers from 1 to 10: To obtain nonunit spacing, specify an increment. For example, 100:-7:50 is

15 The Colon Operator Subscript expressions involving colons refer to portions of a matrix. A(1:k, j) is the first k elements of the jth column of A colon by itself refers to all the elements in a row or column of a matrix. A( :, 1) A( 2, :)

16 Some Other Good Operations To swap the two middle columns. A = B(:,[ ]) To Erase an entire row or column A(1,:)=[] To Add a new row or column B=[A;[ ]]

17 Variable MATLAB does not require any type declarations or dimension statements. the variable already exists, MATLAB changes its contents MATLAB is case sensitive To view the matrix assigned to any variable, simply enter the variable name

18 Format All computations in MATLAB are done in double precision. FORMAT may be used to switch between different output display formats as follows: FORMAT Default. Same as SHORT. FORMAT SHORT Scaled fixed point format with 5 digits FORMAT LONG Scaled fixed point format with 15 digits FORMAT HEX Hexadecimal format.

19 Cell Arrays They are multidimensional arrays whose elements are copies of other arrays. Example: >>C = {A sum(A) prod(prod(A))} ans= C = [4x4 double] [1x4 double] [ ] If you subsequently change A, nothing happens to C

20 useful constants. Pi iImaginary unit sqrt(-1) jSame as i epsFloating-point relative precision realmin Smallest floating-point number, realmax Largest floating-point number, InfInfinity NaNNot-a-number

21 Operations + Addition - Subtraction * Multiplication / Division \ Left division (described in "Matrices and Linear Algebra" in the MATLAB documentation) ^ Power Complex conjugate transpose ( ) Specify evaluation order

22 Example [1+j 2+2*j]' ans = i i >>3/10 ans = >> 10\3 ans =

23 rho = (1+sqrt(5))/2 rho = a = abs(3+4i) a = 5 z = sqrt(besselk(4/3,rho-i)) z = i huge = exp(log(realmax)) huge = e+308 toobig = pi*huge toobig = Inf

24 Generating Matrices Z = zeros(2,4) Z = F = 5*ones(3,3) F = N = fix(10*rand(1,10)) N = R = randn(4,4) R =

25 Some Useful functions A' d = det(A) X = inv(A) e = eig(A) poly(A) sin(x) sinh(x) asin(x)

26 Array Operators + Addition - Subtraction.* Element-by-element multiplication./ Element-by-element division.\Element-by-element left division.^Element-by-element power.' Unconjugated array transpose

27 Example n = (0:9)'; Then pows = [n n.^2 2.^n] builds a table of squares and powers of 2. pows =

28 >> a=[ ] >> b=[ ]' >> a*b ans = 30 >> b*a ans = >> a.*b' ans =

29 B = >>B(1:2,2:3) = 0 B =

30 Geraphics PLOT: x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function','FontSize',12)

31

32 Multiple Data Sets in One Graph y2 = sin(x-.25); y3 = sin(x-.5); plot(x,y,x,y2,x,y3)

33

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

35 plot(x,y,'ks')

36 plot(x,y,'k>')

37 plot(x,y,'r:+')

38 This example plots the data twice using a different number of points for the dotted line and marker plots. x1 = 0:pi/100:2*pi; x2 = 0:pi/10:2*pi; plot(x1,sin(x1),'r:',x2,sin(x2),'r+')

39

40 Complex Data When the arguments to plot are complex, the imaginary part is ignored For the special case of giving the plot a single complex argument, the command is a shortcut for a plot of the real part versus the imaginary part. Therefore, plot(Z)where Z is a complex vector or matrix, is equivalent to plot(real(Z),imag(Z))

41 Adding Plots to an Existing Graph hold on Example: [x,y,z] = peaks; contour(x,y,z,20,'k') hold on pcolor(x,y,z) shading interp hold off

42 Multiple Plots in One Figure subplot(m,n,p) Example: t = 0:pi/10:2*pi; [X,Y,Z] = cylinder(4*cos(t)); subplot(2,2,1); mesh(X) subplot(2,2,2); mesh(Y) subplot(2,2,3); mesh(Z) subplot(2,2,4); mesh(X,Y,Z)

43

44 Setting Axis axis([xmin xmax ymin ymax zmin zmax]) axis auto axis on axis off grid on grid off

45 Example t = -pi:pi/100:pi; y = sin(t); plot(t,y) axis([-pi pi -1 1]) xlabel('-\pi \leq {\itt} \leq \pi') ylabel('sin(t)') title('Graph of the sine function') text(1,-1/3,'{\itNote the odd symmetry.}')

46

47 Mesh and Surface Plots Mesh (x,y,z) produces wireframe surfaces that color only the lines connecting the defining points. surf (x,y,z) displays both the connecting lines and the faces of the surface in color.

48 [X,Y] = meshgrid(-8:.5:8); R = sqrt(X.^2 + Y.^2) + eps; Z = sin(R)./R; mesh(X,Y,Z,'EdgeColor','black')

49 transparency hidden off

50 Surf Example surf(X,Y,Z) colormap hsv colorbar

51 View view(az,el) view([az,el])

52 Surface Plots with Lighting surf(X,Y,Z,'FaceColor','red','EdgeColor','none'); camlight left; lighting phong view(-15,65)

53 Flow Control if rem(n,2) ~= 0 ……………. elseif rem(n,4) ~= 0 ……………… else ………………. end

54 Important! when A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the result is another matrix of 0's and 1's showing element-by-element equality. Solution: if isequal(A,B),...

55 Some Other Helpful Functions Isequal(A,B,…): Determine if arrays are numerically equal Isempty(A): Determine if item is an empty array isequalwithequalnans(A,B,...): Determine if arrays are numerically equal, treating NaNs as equal ismember(A,S): Detect members of a specific set isnumeric(A): Returns logical true (1) if A is a numeric array and logical false (0) otherwise.

56 Some Other Helpful Functions isprime(A): returns an array the same size as A containing logical true (1) for the elements of A which are prime. isreal(A): returns logical false (0) if any element of array A has an imaginary component, even if the value of that component is 0. ischar(A): ischar(A) returns logical true (1) if A is a character array and logical false (0) otherwise.

57 all(A): If A is a vector, all(A) returns logical true (1) if all of the elements are nonzero, and returns logical false (0) if one or more elements are zero. If A is a matrix, all(A) treats the columns of A as vectors, returning a row vector of 1s and 0s.

58 B = any(A): If A is a vector, any(A) returns logical true (1) if any of the elements of A are nonzero, and returns logical false (0) if all the elements are zero. If A is a matrix, any(A) treats the columns of A as vectors, returning a row vector of 1s and 0s.

59 Example: >>A = [ ] B = (A < 0.5) Ans= >>all(B) Ans=0 >>any(B) Ans=1 تابع ماتريسي

60 Relational Operators A < B A > B A <= B A >= B A == B A ~= B EXAMPLE: >>X = 5*ones(3,3); >>X >= [1 2 3; 4 5 6; ]; ans =

61 Logical Operators The precedence for the logical operators The truth table The second operand is evaluated only when the result is not fully determined by the first operand.

62 Example >>u = [ ]; >>v = [ ]; >>u | v ans = to avoid generating a warning when the divisor, b, is zero. x = (b ~= 0) && (a/b > 18.5) Logical Operation on Elements Short Circuit and

63 Flow Control switch (rem(n,4)==0) + (rem(n,2)==0) case 0 ……………………. case 1 ……………………. case 2 ……………………… otherwise error('This is impossible') end

64 Important! Unlike the C language switch statement, MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required.

65 Flow Control for variable = scalar1 : step : scalar2 statement 1... statement n end Example:a = zeros(k,k) % Preallocate matrix for m = 1:k for n = 1:k a(m,n) = 1/(m+n -1); end

66 while expression statements End The statements are executed while the real part of expression has all nonzero elements.

67 Two Useful Functions for Loops Continue: Passes control to the next iteration of for or while loop Break: statement lets you exit early from a for or while loop.

68 Characters and Numbers To define a string: >>s = 'Hello characters are stored as numbers, but not in floating-point format. To see the characters as numbers: >>a = double(s) a = To reverses the conversion: >>s = char(a)

69 M-files: 1.Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. 2.Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.

70 Functions 1.Checks to see if the name is a variable. 2.Checks to see if the name is an internal function (eig, sin) that was not overloaded. 3.Checks to see if the name is a local function (local in sense of multifunction file). 4.Checks to see if the name is a function in a private directory. 5.Locates any and all occurrences of function in method directories and on the path. Order is of no importance. At execution, MATLAB: 6.Checks to see if the name is wired to a specific function (2, 3, & 4 above) 7.Uses precedence rules to determine which instance from 5 above to call (we may default to an internal MATLAB function). Constructors have higher precedence than anything else.

71 Functions nargin and nargout indicate how many input or output arguments, respectively, a user has supplied. if nargout == 0 plot(x,y) else x0 = x; y0 = y; end if nargin < 5, subdiv = 20; end if nargin < 4, angl = 10; end if nargin < 3, npts = 25; end

72 function [x0,y0] = myplot(fname,lims,npts,angl,subdiv) % MYPLOT Plot a function. % MYPLOT(fname,lims,npts,angl,subdiv) % The first two input arguments are % required; the other three have default values.... if nargin < 5, subdiv = 20; end if nargin < 4, angl = 10; end if nargin < 3, npts = 25; end... if nargout == 0 plot(x,y) else x0 = x; y0 = y; end function h = falling(t) global GRAVITY h = 1/2*GRAVITY*t.^2;

73 A review on Mathematical Functions Binary additionA+Bplus(A,B) Unary plus +Auplus(A)Binary Subtraction A-Bminus(A,B) Unary minus-Auminus(A)Matrix MultiplicationA*Bmtimes(A,B)Array-wise Multiplication A.*Btimes(A,B)Matrix right DivisionA/Bmrdivide(A,B)Array-wise right DivisionA./Brdivide(A,B)Matrix left DivisionA\Bmldivide(A,B)Array-wise left DivisionA.\Bldivide(A,B)Matrix PowerA^Bmpower(A,B)Array-wise PowerA.^Bpower(A,B)Complex TransposeActranspose(A)Matrix TransposeA.transpose(A)


Download ppt "An Introduction to MATLAB® Dr M Ali Ahmadi-Pajouh KN Toosi University."

Similar presentations


Ads by Google