SESSION-1       INTRODUCTION TO    PROGRAMMING IN MATLAB          LANGUAGE1                           S YADAV
Programming Basics         To Start Matlab         On Microsoft® Windows® platforms,         double-clicking the MATLAB ...
Programming in Matlab 3                      S YADAV
Basics of Matlab        Matlab has two different methods for executing commands      Interactive mode          In interac...
Scripts and Functions        M-Files:        Files that contain code in the MATLAB language       are called M-files. You ...
Example     Scripts       x = -pi:0.01:pi;       plot(x,sin(x)), grid on    Function       %Name of function is sum1  ...
Variables       As in programming languages, the MATLAB language provides        mathematical expressions, but unlike mos...
MATLAB AND MATRIX8                       S YADAV
MATRIX    *MATLAB IS MATRIX MANIPULATION LANGUAGE.    *MOST OF VARIABLES YOU DECLARE WILL BE    MATRICES.    *MATRIX IS RE...
DEFINING MATRIX IN MATLABLet matrixB=   1   2     3   6   7     8B CAN BE CREATE IN MATLAB USING SYNTAXB=[1 2 3;6 7 8];HOW...
ACCESSING SUBMATRICESA=  11   12      13    14       15    16  17   18      19    20       21    22  23   24      25    26...
ONE DIMENTION MATRIXONE DIMENTION MATRIX IS ALSO KNOWN AS VECTOR.ONE DIMENTION MATRIX MAY BE EITHERROW MATRIX : CONTAINING...
ALTERNATE WAY OF MAKING MATRICESA=1:9A=  1     2     3   4   5   6   7    8   9A=1:2:9A=  1     3     5   7   9A=[5:-1:-5]...
MATRIX BUILDING FUNCTIONS    eyes(n)           will produce nxn identity matrixeyes(m,n)         will produce mxn identity...
MATRIX OPERATIONS+     ADDITION-     SUBTRACTION*     MULTIPLICATION^     POWER‘     CONJUGATE TRANSPOSE.’    TRANSPOSE   ...
EXAMPLE OF MULTIPLICATIONA=                    B= 1    2                   1   1 2    3                   1   1A*B      1*...
ENTRY-WISE OPERATIONS•OPERATIONS OF ADDITION AND SUBTRACTION ALREADYOPERATE ENTRY WISEA=                   B=  1   2      ...
Other entry-wise operationi.e.   .* , .^ , ./ ,.A=[1 2 3 4]B=[1 2 3 4]A.*B=[1 4 9 16]A=[4 6 8 10]B=[2 2 2 2]A./B=[2 3 4 5]...
MATRIX DIVISIONIF A IS AN INVERTIBLE MATRIX AND b IS A COMPATIBLECOLUMN VECTOR, thenx=Ab is the solution of A*x=b[1 2 3;4 ...
STATEMENTS, EXPRESIONS AND               VARIABLES•MATLAB is interpreted language.•Statements are of form   variable=expre...
Continued …..•Statement is terminated with ‘;’•If it is not terminated with ‘;’ , result will be displayed onscreen.•State...
Continued…..•VARIABLE OR FUNCTION CAN BE CLEARED FROMWORKSPACE clear variablename clear functionname•clear WILL CLEAR ALL ...
CONTROL STRUCTURES          IN MATLAB23                        S YADAV
RELATIONAL OPERATORS<    LESS THAN>    GREATER THAN<=   LESS THAN OR EQUAL>=   GREATER THAN OR EQUAL==   EQUAL~=   NOT EQU...
OUTPUT OF RELATIONS OPRATIONWHEN APPLIED TO SCALAR, RELATION IS ZERO OR ONEDEPENDING ON WHETHER THE RELATION IS TRUE OR FA...
Control statement    If ,if else    For loop    While loop    Switch case    Brake ,continue etc.26                  ...
IF price=4500; if price >5000,     disp(PRICE IS MORE THAN 5000); end27                                      S YADAV
IF ELSEprice=4500;if price >5000,  disp(PRICE IS MORE THAN 5000);else  disp(‘PRICE IS NOT MORE THAN 5000’);end 28         ...
IF ELSEIFprice=4500;if price >5000,     disp(PRICE IS MORE THAN 5000);elseif (1000<=price)&(price <=5000),     disp(PRICE ...
WHILE LOOPvar=20;while var>0,  disp(var);  var=var-1;enddisp(variable is zero now);disp(var); 30                          ...
FOR LOOPfor i=1:10,  disp(i);endfor i=1:2:11,  disp(i)end31                         S YADAV
Nested For Loopn=3;for i=1:n,  for j=1:n,       a(i,j)=5;  endenddisp(a);32                                   S YADAV
SWITCH CASEvar1=10;var2=5;switch operationcase add  output=var1+var2;  disp(output);case {multiply,product}  output=var1*v...
CONTINUED ……….case {subtract,sub}  output=var1-var2;  disp(output);case divide  output=var1/var2;  disp(output);otherwise ...
CONTINUED…….case {subtract,sub}  output=var1-var2;  disp(output);case divide  output=var1/var2;  disp(output);otherwise  d...
BREAK STATEMENTvar=20;while var>0,  disp(var);  if var==10      break;  end  var=var-1;endstr=sprintf(Now variable is %d,v...
FUNCTION IN MATLAB37                   S YADAV
SCALAR FUNCTIONS•Operate essentially on scalars.•Operate element-wise when applied to a matrix.sin                       a...
VECTOR FUNCTIONS•OPERATE ESSENTIALY ON VECTOR (ROW OR COLUMN)•WHEN APPLIED TO MxN MATRIX, OPERATE COLUMN BYCOLUMN TO PRODU...
MATRIX FUNCTIONSeig     eigenvalues and eigenvectorschol    cholesky factorizationsvd     singular value decompositioninv ...
STRING FUNCTIONSstrcmp(str1,str2)strncmp(str1,str2,n)strcat(str1,str2)str2num(str)str2double(str)num2str(num)CAT(DIM,A,B) ...
WRITING FUNCTIONfunction [sum,diff]= addsub(a,b)%This function returns two outputs, sum%and differencesum=a+b;diff=a-b;ret...
FUNCTION CONTINUEDfunction result=perform(operation ,var1,var2)switch operationcase multiply   result=var1*var2;case add  ...
INPUTname=input(Please enter your name : ,s);fprintf(nHello %s !n,name);account=input( Please enter your account number : ...
FORMATED OUTPUTname=‘svits;age=06;salary=1800000;fprintf(n Institute Name : %st Age : %d ….t Salary : Rs %0.2f,name,age,sa...
Thank you46               S YADAV
Upcoming SlideShare
Loading in...5
×

Basics of programming in matlab

788

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
788
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
145
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Basics of programming in matlab

  1. 1. SESSION-1 INTRODUCTION TO PROGRAMMING IN MATLAB LANGUAGE1 S YADAV
  2. 2. Programming Basics  To Start Matlab  On Microsoft® Windows® platforms, double-clicking the MATLAB shortcut on your Windows desktop. Matlab.ico  On UNIX platforms, start MATLAB by typing matlab at the operating system prompt. Quitting the MATLAB Program  To end your MATLAB session, select File > Exit MATLAB in the desktop, or type quit in the Command2 Window S YADAV
  3. 3. Programming in Matlab 3 S YADAV
  4. 4. Basics of Matlab  Matlab has two different methods for executing commands Interactive mode In interactive mode, commands are typed (or cut-and-pasted) into the command window.  »3+ 4  ans =  7  Batch mode. In batch mode, a series of commands are saved in a text file (either using Matlabs built-in editor, or another text editor ) with a .m extension. The batch commands in a file are then executed by typing the name of the file at the Matlab command prompt.4 S YADAV
  5. 5. Scripts and Functions M-Files: Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB function or command.  There are two kinds of 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. NOTE :The names of the M-file and of the function should be the same.5 S YADAV
  6. 6. Example Scripts  x = -pi:0.01:pi;  plot(x,sin(x)), grid on Function  %Name of function is sum1  function c=sum1(a,b)  c=a+b  end  M file names should be sum1.m6 S YADAV
  7. 7. Variables  As in programming languages, the MATLAB language provides mathematical expressions, but unlike most programming languages, these expressions involve entire matrices.  MATLAB does not require any type declarations or dimension statements. When MATLAB encounters a new variable name, it automatically creates the variable and allocates the appropriate amount of storage. If the variable already exists, MATLAB changes its contents and, if necessary, allocates new storage. For example,  num_students = 25 creates a 1-by-1 matrix named num_students and stores the value 25 in its single element. To view the matrix assigned to any variable, simply enter the variable name.  Variable names consist of a letter, followed by any number of letters, digits, or underscores.(max length of variable is 63)  MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. B and b are not the same variable.7 S YADAV
  8. 8. MATLAB AND MATRIX8 S YADAV
  9. 9. MATRIX *MATLAB IS MATRIX MANIPULATION LANGUAGE. *MOST OF VARIABLES YOU DECLARE WILL BE MATRICES. *MATRIX IS RECTANGULAR ARRAY OF NUMBERS *A is MxN MATRIX : IT MEANS ‘A’ HAS M ROWS AND N COLUMNS *IN MATRIX FIRST INDEX IS ROW INDEX AND SECOND INDEX IS COLUMN INDEX *SCALAR IS 1x1 MATRIX. *INDEXING IN MATLAB STARTS FROM ONE(1)9 S YADAV
  10. 10. DEFINING MATRIX IN MATLABLet matrixB= 1 2 3 6 7 8B CAN BE CREATE IN MATLAB USING SYNTAXB=[1 2 3;6 7 8];HOW TO ACCESS DIFFERENT ELEMENTS B(ROW ,COLUMN)B(1,1)=1 i.e. FIRST ROW and FIRST COLUMNB(2,1)=6 i.e. SECOND ROW FIRST COLUMN B(2,3)=8 i.e. SECOND ROW THIRD COLUMN10 S YADAV
  11. 11. ACCESSING SUBMATRICESA= 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28A(1,:) = [11 12 13 14 15 16]i.e. FIRST ROW AND ALL COLUMNSA(2,:)=[17 18 19 20 21 22]i.e. SECOND ROW AND ALL COLUMNSA(1,1:3)=[11 12 13 ];i.e. FIRST ROW AND ONE TO THREE COLUMNSA(2,3:6)=[19 20 21 22 ]; i.e second row , third to sixth column. 11 S YADAV
  12. 12. ONE DIMENTION MATRIXONE DIMENTION MATRIX IS ALSO KNOWN AS VECTOR.ONE DIMENTION MATRIX MAY BE EITHERROW MATRIX : CONTAINING ONE ROW ONLYORCOLUMN MATRIX:CONTAINING ONE COLUMN ONLYHOW TO ACCES DIFFERENT ELEMENTSA(1),A(2) WILL WORK AS IT IS ONE DIMENSIONAL VECTOR.12 S YADAV
  13. 13. ALTERNATE WAY OF MAKING MATRICESA=1:9A= 1 2 3 4 5 6 7 8 9A=1:2:9A= 1 3 5 7 9A=[5:-1:-5]A= 5 4 3 2 1 0 -1 -2 -3 -4 -5 13 S YADAV
  14. 14. MATRIX BUILDING FUNCTIONS eyes(n) will produce nxn identity matrixeyes(m,n) will produce mxn identity matrixones(n) will produce nxn matrix of ones.ones(m,n) will produce mxn matrix of ones.zeros(m,n) will produce matrix of zerosrand(m,n) will produce mxn matrix of randomvaluetriu(X) will extract upper triangular part of matrix X.tril(X) will extract lower triangular part of matrix X.14 S YADAV
  15. 15. MATRIX OPERATIONS+ ADDITION- SUBTRACTION* MULTIPLICATION^ POWER‘ CONJUGATE TRANSPOSE.’ TRANSPOSE LEFT DIVISION/ RIGHT DIVISIONTHESE MATRIX OPERATIONS APPLY TO SCALARS AS WELL.IF THE SIZES OF MATRICES ARE INCOMPATIBLE FOR THEMATRIX OPERATION, AN ERROR MESSAGE WILL RESULT. 15 S YADAV
  16. 16. EXAMPLE OF MULTIPLICATIONA= B= 1 2 1 1 2 3 1 1A*B 1*1+2*1 1*1+2*1 2*1+3*1 2*1+3*1A*B 3 3 5 516 S YADAV
  17. 17. ENTRY-WISE OPERATIONS•OPERATIONS OF ADDITION AND SUBTRACTION ALREADYOPERATE ENTRY WISEA= B= 1 2 1 1 2 1 1 1A+B 2 3 3 217 S YADAV
  18. 18. Other entry-wise operationi.e. .* , .^ , ./ ,.A=[1 2 3 4]B=[1 2 3 4]A.*B=[1 4 9 16]A=[4 6 8 10]B=[2 2 2 2]A./B=[2 3 4 5]A=[1 2 3]A.^3=[1 8 27] 18 S YADAV
  19. 19. MATRIX DIVISIONIF A IS AN INVERTIBLE MATRIX AND b IS A COMPATIBLECOLUMN VECTOR, thenx=Ab is the solution of A*x=b[1 2 3;4 5 6; 8 9 7]*[x;y;z]=[1;2;3][x;y;z]=[1 2 3;4 5 6;8 9 7][1;2;3]IF A IS AN INVERTIBLE MATRIX AND b IS A COMPATIBLEROW VECTOR, thenx=b/A is the solution of x*A=b[x y z]*[1 2 3;4 5 6; 8 9 7]=[1 1 3][x y z]=[1 1 3]/[1 2 3;4 5 6;8 9 7] 19 S YADAV
  20. 20. STATEMENTS, EXPRESIONS AND VARIABLES•MATLAB is interpreted language.•Statements are of form variable=expression; expression; x=3;y=x^3+3*x;y=sqrt(x);Or justx^3+2*x ;In this case variable ‘ans’ is automatically created to whichresult is assigned 20 S YADAV
  21. 21. Continued …..•Statement is terminated with ‘;’•If it is not terminated with ‘;’ , result will be displayed onscreen.•Statements can be placed on same line if they are terminatedwith ‘;’•Single statement can be continued to next line with three ormore periods e.g. y=x*x+ ….. 2*x+3;•MATLAB is case sensitive.•who or whos will list variables in current workspace.•inmem lists compiled m files in current memory. 21 S YADAV
  22. 22. Continued…..•VARIABLE OR FUNCTION CAN BE CLEARED FROMWORKSPACE clear variablename clear functionname•clear WILL CLEAR ALL NON PERMANENT VARIABLES.•ON LOGOUT ALL VARIABLES ARE LOST•‘save’ WILL SAVE ALL VARIABLES IN FILE matlab.mat•‘load’ WILL RESTORE WORKSPACE TO ITS FORMAL STATE.•‘save’ and ‘load’ TAKE VARIABLE NAME AND FILENAME ASOPTIONAL ARGUMENTS.•edit fun opens the file fun.m in a text editor.22 S YADAV
  23. 23. CONTROL STRUCTURES IN MATLAB23 S YADAV
  24. 24. RELATIONAL OPERATORS< LESS THAN> GREATER THAN<= LESS THAN OR EQUAL>= GREATER THAN OR EQUAL== EQUAL~= NOT EQUALNOTE: = IS USED IN ASSIGNMENT AND = = IS USED IN ARELATIONLOGICAL OPERATORS& AND| OR~ NOTRELATIONS MAY BE CONNECTED BY LOGICAL OPERATORS24 S YADAV
  25. 25. OUTPUT OF RELATIONS OPRATIONWHEN APPLIED TO SCALAR, RELATION IS ZERO OR ONEDEPENDING ON WHETHER THE RELATION IS TRUE OR FALSEa=3; b=2;c= ( a>b) ; It means c=1c=(a<b); It means c=0a= = b answer is 0a~=b answer is 1AND WHEN APPLIED TO MATRICES OF SAME SIZE, RELATIONIS MATRIX OF 0’s and 1’s GIVING VALUE OF RELATIONBETWEEN CORROSPONDING ENTERIES.d=[1 2]; e=[1 1];f= (d= =e); It means f=[1 0];25 S YADAV
  26. 26. Control statement  If ,if else  For loop  While loop  Switch case  Brake ,continue etc.26 S YADAV
  27. 27. IF price=4500; if price >5000, disp(PRICE IS MORE THAN 5000); end27 S YADAV
  28. 28. IF ELSEprice=4500;if price >5000, disp(PRICE IS MORE THAN 5000);else disp(‘PRICE IS NOT MORE THAN 5000’);end 28 S YADAV
  29. 29. IF ELSEIFprice=4500;if price >5000, disp(PRICE IS MORE THAN 5000);elseif (1000<=price)&(price <=5000), disp(PRICE IS BETWEEN 1000 AND 5000);else disp(PRICE IS LESS THAN 1000);end29 S YADAV
  30. 30. WHILE LOOPvar=20;while var>0, disp(var); var=var-1;enddisp(variable is zero now);disp(var); 30 S YADAV
  31. 31. FOR LOOPfor i=1:10, disp(i);endfor i=1:2:11, disp(i)end31 S YADAV
  32. 32. Nested For Loopn=3;for i=1:n, for j=1:n, a(i,j)=5; endenddisp(a);32 S YADAV
  33. 33. SWITCH CASEvar1=10;var2=5;switch operationcase add output=var1+var2; disp(output);case {multiply,product} output=var1*var2; disp(output); 33 S YADAV
  34. 34. CONTINUED ……….case {subtract,sub} output=var1-var2; disp(output);case divide output=var1/var2; disp(output);otherwise disp(What else you want?);end 34 S YADAV
  35. 35. CONTINUED…….case {subtract,sub} output=var1-var2; disp(output);case divide output=var1/var2; disp(output);otherwise disp(What else you want?);end 35 S YADAV
  36. 36. BREAK STATEMENTvar=20;while var>0, disp(var); if var==10 break; end var=var-1;endstr=sprintf(Now variable is %d,var);disp(str); 36 S YADAV
  37. 37. FUNCTION IN MATLAB37 S YADAV
  38. 38. SCALAR FUNCTIONS•Operate essentially on scalars.•Operate element-wise when applied to a matrix.sin asin expabs cos acoslog10 log (natural log) sqrtfloor tan atanrem (remainder) signroundA=sin(1)A= 0.8415A=sin([1 1.2 1.3 1.4])A= 0.8415 0.9320 0.9636 0.985438 S YADAV
  39. 39. VECTOR FUNCTIONS•OPERATE ESSENTIALY ON VECTOR (ROW OR COLUMN)•WHEN APPLIED TO MxN MATRIX, OPERATE COLUMN BYCOLUMN TO PRODUCE ROW VECTOR CONTAINING RESULTOF APPLICATION TO EACH COLUMN.max sum medianany min prodmean all sortstdmax([1 2 3])ans = 3max([1 2 3 589 7 6 2])ans = 39 8 9 7 S YADAV
  40. 40. MATRIX FUNCTIONSeig eigenvalues and eigenvectorschol cholesky factorizationsvd singular value decompositioninv inverselu LU factorizationqr QR factorizationrref reduced row echelon formexpm matrix exponential40 S YADAV
  41. 41. STRING FUNCTIONSstrcmp(str1,str2)strncmp(str1,str2,n)strcat(str1,str2)str2num(str)str2double(str)num2str(num)CAT(DIM,A,B) concatenates the arrays A and B along the dimensionDIM. CAT(2,A,B) is the same as [A,B]. CAT(1,A,B) is the same as [A;B]. 41 S YADAV
  42. 42. WRITING FUNCTIONfunction [sum,diff]= addsub(a,b)%This function returns two outputs, sum%and differencesum=a+b;diff=a-b;return;42 S YADAV
  43. 43. FUNCTION CONTINUEDfunction result=perform(operation ,var1,var2)switch operationcase multiply result=var1*var2;case add result=var1+var2;case subtract result=var1-var2;case divide result=var1/var2;otherwise disp(Only multilply, add,subtract and divide operations areallowed); result=error; 43end S YADAV
  44. 44. INPUTname=input(Please enter your name : ,s);fprintf(nHello %s !n,name);account=input( Please enter your account number : );if (25 <account)&(account<50) disp(Welcome);else disp(You are not a valid user);end 44 S YADAV
  45. 45. FORMATED OUTPUTname=‘svits;age=06;salary=1800000;fprintf(n Institute Name : %st Age : %d ….t Salary : Rs %0.2f,name,age,salary);fprintf(n I am writing 123456 in exponential ….form : %e,12356);a=[1.2 1.3 1.4 1.5 1.6];fprintf(n %f ,a); 45 S YADAV
  46. 46. Thank you46 S YADAV
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×