home *** CD-ROM | disk | FTP | other *** search
/ Math Solutions 1995 October / Math_Solutions_CD-ROM_Walnut_Creek_October_1995.iso / pc / mac / diffequa / numerica / notes.m < prev    next >
Encoding:
Text File  |  1995-04-05  |  11.5 KB  |  608 lines

  1. %NOTES
  2.  
  3. MATLAB Preliminaries
  4.  
  5. Matlab File types
  6.   Scripts    are used for storing several executable statements.
  7.   Functions  are used for functions and subroutines.
  8.   MAT-files  are used for storing data.
  9.  
  10. Editing
  11.  
  12.   The command window.
  13.   
  14. 1. The command window is used for immediate mode entering and display 
  15.    of variables and execution of a MATLAB command. 
  16.  
  17. 2. The command window is used for execution of a functions, subroutines 
  18.    and programs that are stored in an  M-File .
  19.  
  20.   The edit window.
  21.   
  22. 1. The edit window is write and edit functions, subroutines and programs 
  23.    which are to be stored in an  M-File. 
  24.  
  25.   The graph window
  26.  
  27. 1. The graph window is used to view plotted data.
  28.  
  29. Diary
  30.   Diary <filename>  directs output to the file
  31.   Diary off         suspends the diary
  32.   Diary on          turns diary on again
  33.  
  34. Conservation of resources
  35.  
  36.   Most numerical experiments involve columns of numbers which might extend 
  37. several pages.  It is not necessary to see all of the computations in a project.
  38. Judicious use of diary and files commands such as X(1:5:N) will reduce the 
  39. amount of paperwork.  Before you hand in a project, determine how little is required.
  40.  
  41.  
  42. Obtaining Help
  43.  
  44.   HELP topic  gives help on the topic.
  45.   HELP word  where 'word' is a filename, 
  46.           displays the first comment lines in the M-file 'word.m'.
  47.  
  48. Housekeeping
  49.  
  50.   ;      Place at the end of line to suppress the computer echo.
  51.   ,      Used at the end of a line if the computer echo is desired.
  52.   %      This is a comment.
  53.  
  54.   format short        output displays four decimal places
  55.   format long         output displays fourteen decimal places
  56.   who                 list of variables
  57.   what                list of files
  58.   clear               clear workspace
  59.   clear variables     clear variables
  60.   clear functions     clear functions
  61.   clc                 clear display
  62.   clg                 clear graph
  63.  
  64. Assignment Statements
  65.  
  66.   »x = 2;
  67.   »y = x^2 -3*x + 2;
  68.  
  69. Form of a MATLAB Program M-File of executable statements
  70.  
  71. %  <program-name>
  72. {<specification-statements>}
  73. {<executable-statements>}
  74.  
  75. Form of a MATLAB Subroutine M-File
  76.  
  77. function (output-list) = <subroutine-name> (argument-list)
  78. {<specification-statements>}
  79. {<executable-statements>}
  80.  
  81. Example, store the following subroutine in the M-file;  sroot.m
  82.  
  83. function  r = sroot(A)
  84. % Newton's method to find  A^(1/2)
  85. p0 = 1;                             % Starting value.
  86. for k=1:50,
  87.   p1 = (p0+A/p0)/2;
  88.   disp(p1);
  89.   if abs(p1-p0)/p1 < eps, break, end;
  90.   p0 = p1;
  91. end
  92.  
  93. Form of a function (or subroutine) call.
  94.  
  95. »  sroot(5)
  96.  
  97.    3
  98.    2.33333333333333
  99.    2.23809523809524
  100.    2.23606889564336
  101.    2.23606797749998
  102.    2.23606797749979
  103.    2.23606797749979
  104.  
  105.  
  106. Form of a MATLAB function M-File
  107.  
  108. function <output-list> = <function-name> (argument-list)
  109. {<specification-statements>}
  110. {<executable-statements>}
  111. <output-name> = <returned computation>
  112.  
  113.   Store the following functions in the M-files:  f.m  and  G.m
  114.  
  115. function y = f(x)
  116. y = exp(-x./10) + sin(x);
  117.  
  118. function W = G(Z)       % Z is a 1 by 2 vector
  119. x = Z(1);
  120. y = Z(2);
  121. W = [x.^2-y.^2  2*x.*y];
  122.  
  123. Form of a Function call.
  124. »f(pi/2)
  125.  
  126.   ans =
  127.     1.85463599915323
  128.  
  129. »G([2 1])
  130.  
  131.   ans =
  132.     3     4
  133.  
  134. Arrays
  135.  
  136.   All variable in MATLAB are treated as arrays. A scalar is a one by one array.
  137.   Initialization can fill an array with either zeros or ones.
  138.  
  139. »Z = zeros(1,5)         % Initialize a row vector with zeros.
  140.  
  141.   Z =
  142.     0     0     0     0     0
  143.  
  144. »W = zeros(3,1)         % Initialize a column vector with zeros.
  145.  
  146.   W =
  147.     0
  148.     0
  149.     0
  150.  
  151. »M = ones(2,4)          % Initialize a matrix with ones.
  152.  
  153.   M =
  154.     1     1     1     1
  155.     1     1     1     1
  156.  
  157. »size(M)
  158.  
  159.   ans =
  160.     2     4
  161.  
  162. Vectors
  163.  
  164.   Vectors can be entered and stored as a matrix with one row or one column
  165.  
  166. »V = [1,2,3,4]
  167.  
  168.   V =
  169.     1     2     3     4
  170.  
  171.  
  172. »length(V)
  173.  
  174.   ans =
  175.     4
  176.  
  177. »sum(V)         % The sum of the elements of V.
  178.  
  179.   ans =
  180.     10
  181.  
  182. »mean(V)        % The mean of the elements of V.
  183.  
  184.   ans =
  185.     2.5000
  186.  
  187.  
  188. Transpose 
  189.  
  190. »W =  [1,
  191.      2,
  192.      3,
  193.      4]
  194.  
  195.   W =
  196.        1
  197.        2
  198.        3
  199.        4
  200. »W'
  201.  
  202.   ans =
  203.     1     2     3     4
  204.  
  205. Colon
  206.  
  207.   Used for creating a list and it is used for selecting part(s) of a list.
  208.  
  209. »X = 1:20;          % A list of integers from 1 to 20.
  210. »Y = X.^2;          % A list of their squares.
  211. »Y(10:20)           % Display only the last 11 entries.
  212.  
  213.   ans =
  214.     100  121  144  169  196  225  256  289  324  361  400
  215.  
  216. »A = [1  2  3  4,
  217.       5  6  7  8,
  218.       9 10 11 12];
  219.  
  220. »A(1,3)             % Select one element in a matrix.
  221.  
  222.   ans =
  223.     3
  224.  
  225. »A(2:3, 1:2)        % Select a sub-matrix.
  226.  
  227.   ans =
  228.     5     6
  229.     9    10
  230.  
  231.  
  232. Arithmetic Operations
  233.  
  234.   +    Addition
  235.   -    Subtraction
  236.   *    Multiplication
  237.   /    Division
  238.   ^    Power
  239.  
  240.  
  241. Arithmetic Operations for arrays (also useful for functions to be plotted)
  242.  
  243.   .+  Element-wise addition
  244.   .-  Element-wise subtraction
  245.   .*  Element-wise multiplication
  246.   ./  Element-wise division  or  use  (  ).^(-1)
  247.   .^  Element-wise power
  248.  
  249. »A = [1 2,
  250.       3 4];
  251. »A^2                 % Square a matrix.
  252.  
  253.   ans =
  254.      7    10
  255.     15    22
  256.  
  257. »A.^2                % Square each element in a matrix.
  258.   ans =
  259.     1     4
  260.     9    16
  261.  
  262. »C = inv(A)          % Find the inverse of a matrix.
  263.   C =
  264.     -2.0000    1.0000
  265.      1.5000   -0.5000
  266.  
  267. »A*C                 % Verify that C is the inverse.
  268.   ans =
  269.     1.0000         0
  270.     0.0000    1.0000
  271.  
  272. Relational Operators
  273.  
  274.   ==   Equal to
  275.   ~=   Not equal to
  276.   <    Less than
  277.   >    Greater than
  278.   <=   Less than or equal to
  279.   >=   Greater than or equal to
  280.  
  281. Logical Operators
  282.  
  283.   ~    Not  Complement
  284.   &    And  True if both operands are true
  285.   |    Or  True if either (or both) operands are true
  286.  
  287. Boolean Values
  288.  
  289.   1    True
  290.   0    False
  291.  
  292. IF (Block) Control Statement
  293.  
  294. Performs the series of {<executable-statement>} following it 
  295. or transfers control to an ELSEIF, ELSE, or ENDIF statement, 
  296. depending on (<logical-expression>).
  297.  
  298. if (<logical-expression#1>),
  299.   {<executable-statements>}
  300. elseif (<logical-expression#2>),
  301.   {<executable-statements>}
  302. end
  303.  
  304.  
  305. if (<logical-expression#1>),
  306.   {<executable-statements>}
  307. elseif (<logical-expression#2>),
  308.   {<executable-statements>}
  309.         
  310. else
  311.   {<executable-statements>}
  312. end
  313.  
  314.  
  315. Break
  316.  
  317. if n==3, break, end
  318.  
  319. for k=1:100,
  320.   x=sqrt(k);
  321.   if x>5, break, end
  322. end
  323.  
  324.  
  325. For loop
  326.  
  327. sum1 = 0;
  328.   for k = 1:1:10000,
  329.   sum1 = sum1 + 1/k;
  330. end
  331. sum1
  332.  
  333.   sum1 =
  334.       9.78760603604434
  335.  
  336. sum2 = 0;
  337. for k = 10000:-1:1,
  338.   sum2 = sum2 + 1/k;
  339. end
  340. sum2
  341.  
  342.   sum2 =
  343.       9.78760603604439
  344.  
  345. for j = 1:5,
  346.   for k = 1:5,
  347.     A(j,k) = 1/(j+k-1);
  348.   end
  349. end
  350. A                        % The 5 by 5 Hilbert matrix A will be displayed.
  351.  
  352.  
  353. While (Block) Control Statement
  354.  
  355. m = 10;
  356. k = 0;
  357. while k<=m
  358.   x = k/10;
  359.   disp([x, x^2, x^3]);   % A table of values will be printed.
  360.   k = k+1;
  361. end
  362.  
  363.  
  364. Pause statement
  365.  
  366.   pause
  367.  
  368. Mathematical functions
  369.  
  370.   cos(x)    cosine (radians)
  371.   sin(x)    sine (radians)
  372.   tan(x)    tangent (radians)
  373.   exp(x)    exponential  exp(x)
  374.   acos(x)   inverse cosine (radians)
  375.   asin(x)   inverse sine (radians)
  376.   atan(x)   inverse tangent (radians)
  377.   log(x)    natural logarithm base  e
  378.   log10(x)  common logarithm base  10
  379.   sqrt(x)   square root
  380.   abs(x)    absolute value
  381.   round(x)  round to nearest integer
  382.   fix(x)    round towards zero
  383.   floor(x)  round towards -∞
  384.   ceil(x)   round towards +∞
  385.   sign(x)   signum function
  386.   cosh(x)   hyperbolic cosine
  387.   sinh(x)   hyperbolic sine
  388.   tanh(x)   hyperbolic tangent
  389.   acosh(x)  inverse hyperbolic cosine
  390.   asinh(x)  inverse hyperbolic sine
  391.   atanh(x)  inverse hyperbolic tangent
  392.   real(z)   real part of complex number z
  393.   imag(z)   imaginary part of complex number z
  394.   conj(z)   complex conjugate of the complex number z
  395.   angle(z)  argument of complex number z
  396.   rem(p,q)  remainder when p is divided by q
  397.  
  398.  
  399. Data Analysis
  400.  
  401.   max       maximum value
  402.   min       minimum value
  403.   mean      mean value
  404.   median    median value
  405.   std       standard deviation
  406.   sort      sorting
  407.   sum       sum the elements
  408.   prod      form product of the elements
  409.   cumsum    cumulative sum of elements
  410.   cumprod   cumulative product of elements
  411.   diff      approximate derivatives (differences)
  412.   hist      histogram
  413.   corrcoef  correlation coefficients
  414.   cov       covariance matrix
  415.  
  416.  
  417. Graphics
  418.  
  419.   Store the following script in the M-file;  sketch.m 
  420.  
  421. X = 0:pi/8:pi;
  422. Y = sin(X);
  423. axis([-0.2 3.2 -0.1 1.1]);
  424. plot(X,Y);
  425. hold on;
  426. plot([-0.2 3.2],[0,0],[0,0],[-0.1 1.1]);
  427. xlabel('x');
  428. ylabel('y');
  429. title('Graph of y = sin(x)');
  430. grid;
  431. axis;
  432. hold off;
  433.  
  434.   Issue the command  sketch  and obtain the graph
  435.  
  436.  
  437.  
  438. Remark. Data used by the plot command must be two vectors of equal length.
  439.   
  440.   X =
  441.     0  0.3927 0.7854 1.1781 1.5708 1.9635 2.3562 2.7489  3.1416
  442.   Y =
  443.     0  0.3827 0.7071 0.9239 1.0000 0.9239 0.7071 0.3827  0.0000
  444.  
  445.  
  446. Polynomial functions
  447.  
  448.   The coefficients of a polynomial are stored as a coefficient list.
  449.  
  450.   »C = [1 -3 2]
  451.   C =
  452.     1    -3     2
  453.  
  454.   If  C  is a vector whose elements are the coefficients  of a polynomial, 
  455.   then polyval(C,x)  is the value of the polynomial evaluated at x.  
  456.  
  457.   »for x=0:0.5:3,
  458.     disp([x,polyval(C,x)]),
  459.   end
  460.  
  461.   0           2
  462.   0.5000      0.7500
  463.   1           0
  464.   1.5000     -0.2500
  465.   2           0
  466.   2.5000      0.7500
  467.   3           2
  468.  
  469.  
  470. Finding the roots of a polynomial.  Let  p(x)  =  x5 - 10x4 + 35x3 - 50x2 + 24
  471.  
  472. »C = [1  -10  35  -50  24]
  473. C =
  474.      1   -10    35   -50   24
  475.  
  476. »roots(C)
  477. ans =
  478.     4.0000
  479.     3.0000
  480.     2.0000
  481.     1.0000
  482.  
  483. Other operations with polynomials are:
  484.  
  485.   conv     polynomial multiplication
  486.   polyfit  polynomial curve fitting
  487.  
  488.  
  489.   Graph the polynomial  p(x)  =  x5 - 10x4 + 35x3 - 50x2 + 24
  490.  
  491.   Store the following script in the M-file;  sketch.m 
  492.  
  493. C = [1  -10  35  -50  24];
  494. X=-0.2:0.1:4.2;
  495. Y=polyval(C,X);
  496. axis([-0.2 4.2 -2.3 4.3]);
  497. plot(X,Y);
  498. hold on;
  499. plot([-0.2 4.2],[0,0],[0,0],[-2.3 4.3]);
  500. xlabel('x');
  501. ylabel('y');
  502. title('Graph of a polynomial.');
  503. grid;
  504. axis;
  505. hold off;
  506.  
  507.   Issue the command  sketch  and obtain the graph.
  508.  
  509.  
  510.  
  511.   For function of the independent variable x one can define f
  512.   as a text string:
  513.  
  514. f = 'sin(x)'
  515.  
  516.   Then use the fplot command
  517.  
  518. fplot(f,[0 10]);
  519.  
  520.  
  521.  
  522. 3-dimensional graphs
  523.  
  524.   Store the following script in the M-file;  sketch.m 
  525.  
  526. [X Y] = meshdom(-1:0.1:1, -1:0.1:1);
  527. Z = X.^2 - Y.^2;
  528. mesh(Z);
  529. title('Graph of z = x^2 - y^2');
  530.  
  531.   Issue the command  sketch  and obtain the graph.
  532.  
  533.  
  534. More commands for matrices
  535.  
  536.   zeros    zero matrix
  537.   ones     matrix of ones
  538.   rand     random elements
  539.   eye      identity matrix
  540.   meshdom  domain for mesh plots
  541.   rot90    rotation of matrix elements
  542.   fliplr   flip matrix left-to-right
  543.   flipud   flip matrix up-and-down
  544.   diag     extract or create diagonal
  545.   tril     lower triangular part
  546.   triu     upper triangular part
  547.   '        transpose
  548.  
  549.  
  550. Solution of a linear system  AX = B
  551.  
  552. »A = [1  2  3  4,    % Enter the matrix A.
  553.       2  5  1  1,
  554.       3  1  2  1,
  555.       4  1  1  3];
  556.  
  557.   A = [1  2  3  4,
  558.        2  5  1  1,
  559.        3  1  2  1,
  560.        4  1  1  3];
  561.  
  562. »B = [2 1 3 4]'      % Enter the vector B.
  563.  
  564.   B =
  565.     2
  566.     1
  567.     3
  568.     4
  569.  
  570. »X = A\B             % Solve the linear system AX = B.
  571.  
  572.   X =
  573.      0.8333
  574.     -0.2273
  575.      0.2576
  576.      0.2121
  577.  
  578. »A*X                 % Verify that X is the solution.
  579.  
  580.   ans =
  581.     2
  582.     1
  583.     3
  584.     4
  585.  
  586.  
  587. Eigenvectors and eigenvalues
  588.  
  589. »A = [1  2  3  4,    % Enter the matrix A.
  590.       2  5  1  1,
  591.       3  1  2  1,
  592.       4  1  1  3];
  593.  
  594. »[V E] = eig(A)      % V is a matrix of eigenvectors.
  595.                      % E is a diagonal matrix of eigenvalues.
  596.  
  597.   V =
  598.     -0.2397   -0.0481   -0.8000    0.5479
  599.      0.8438    0.0977    0.0966    0.5187
  600.     -0.1880   -0.8201    0.3733    0.3908
  601.     -0.4418    0.5618    0.4597    0.5272
  602.  
  603.   E =
  604.     3.6856         0         0         0
  605.          0    1.3717         0         0
  606.          0         0   -2.9395         0
  607.          0         0         0    8.8822
  608.