home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / maths / rlab / docs / RLAB-R~2 < prev    next >
Encoding:
Text File  |  1997-03-09  |  18.0 KB  |  575 lines

  1. <HTML>
  2. <HEAD>
  3. <TITLE> Rlab2 Reference Manual: Tutorial</TITLE>
  4. </HEAD>
  5. <BODY>
  6. <A HREF="rlab-ref-1.html"><IMG SRC="prev.gif" ALT="Previous"></A>
  7. <A HREF="rlab-ref-3.html"><IMG SRC="next.gif" ALT="Next"></A>
  8. <A HREF="rlab-ref.html#toc2"><IMG SRC="toc.gif" ALT="Contents"></A>
  9. <HR>
  10. <H2><A NAME="s2">2. Tutorial</A></H2>
  11.  
  12.  
  13. <P>Now that you have seen how to start Rlab, run a program, get help,
  14. and interpret error messages, you should be ready to try out some
  15. elementary operations. These simple examples are here to help you
  16. ``get your feet wet''. Please read this section in front of a
  17. computer, and try the examples as you read each one.</P>
  18. <P>Since this is a tutorial, every detail and nuance of each example
  19. may not be fully explained. As you work through this section you may
  20. have to take some ideas ``on faith''. However, everything should be
  21. fully explained in subsequent sections of this manual. If you find
  22. something that is not explained, please bring it to the author's
  23. attention.</P>
  24.  
  25.  
  26. <H2><A NAME="ss2.1">2.1 Fundamental Operations</A></H2>
  27.  
  28.  
  29. <P>Rlab does not require definition of variable types and size, Unlike
  30. more conventional languages such as: Fortran, Pascal, and C. This
  31. approach may seem daring at first, but practice has shown that it is
  32. most often a much more productive environment for rapid development
  33. of programs than strictly typed languages.</P>
  34.  
  35. <H3>Creating Matrices / Arrays</H3>
  36.  
  37.  
  38. <P>For starters we will introduce the reader to basic operations that
  39. are used in many applications. The first is to create a matrix or
  40. array of data so that operations can be demonstrated. The matrix
  41. elements are entered at the command line (or in a file). The commas
  42. separate the elements of a row, and the semi-colons separate one row
  43. from the next.</P>
  44. <P>
  45. <BLOCKQUOTE><CODE>
  46. <PRE>
  47. > a = [1,2,3; 4,5,6; 7,8,9]
  48.         1          2          3  
  49.         4          5          6  
  50.         7          8          9  
  51. </PRE>
  52. </CODE></BLOCKQUOTE>
  53. </P>
  54. <P>The commas are <EM>required</EM> so that there are no ambiguities when
  55. more complex expressions are used to create a matrix. For an
  56. example, lets create the Attitude matrix for a 3-2-3 Euler angle
  57. rotation. The variables <CODE>th</CODE>, <CODE>ph</CODE>, and <CODE>ps</CODE>
  58. represent the three Euler angles. To make the notation more concise,
  59. we will make the variables <CODE>c</CODE> and <CODE>s</CODE> copies of the
  60. builtin functions <CODE>sin</CODE> and <CODE>cos</CODE>. Next the matrix is
  61. entered, with the result displayed upon completion.</P>
  62. <P>
  63. <BLOCKQUOTE><CODE>
  64. <PRE>
  65. > th = pi/8; ph = pi/4; ps = pi/16;
  66. > c = cos; s = sin;
  67. > A = [ c(ps)*c(th)*c(ph)-s(ps)*s(ph), c(ps)*c(th)*s(ph)+s(ps)*c(ph), -c(ps)*s(th);
  68. >      -s(ps)*c(th)*c(ph)-c(ps)*s(ph),-s(ps)*c(th)*s(ph)+c(ps)*c(ph),  s(ps)*s(th);
  69. >       s(th)*c(ph),                   s(th)*s(ph),                    c(th) ]
  70.     0.503      0.779     -0.375  
  71.    -0.821      0.566     0.0747  
  72.     0.271      0.271      0.924  
  73. </PRE>
  74. </CODE></BLOCKQUOTE>
  75. </P>
  76. <P>The matrices we have created thus far: <CODE>a</CODE>, and <CODE>A</CODE> are
  77. two-dimensional; they have row and column dimensions. Actually, all
  78. arrays are two-dimensional. Row and column vectors merely have one
  79. dimension equal to one, and scalar values have both dimensions equal
  80. to one.</P>
  81. <P>The <CODE>show</CODE> function displays information about its argument. In
  82. the following example, we see that the entire array <CODE>a</CODE> is a
  83. 3-by-3 matrix, from the numeric class, data type real, and uses
  84. dense storage. Note that the scalar value <CODE>a[1]</CODE> is also the
  85. same kind of object, just with different dimensions.</P>
  86. <P>
  87. <BLOCKQUOTE><CODE>
  88. <PRE>
  89. > show(a);
  90.         nr                  :   3
  91.         nc                  :   3
  92.         n                   :   9
  93.         class               :   num
  94.         type                :   real
  95.         storage             :   dense
  96. > show(a[1]);
  97.         nr                  :   1
  98.         nc                  :   1
  99.         n                   :   1
  100.         class               :   num
  101.         type                :   real
  102.         storage             :   dense
  103. </PRE>
  104. </CODE></BLOCKQUOTE>
  105. </P>
  106.  
  107.  
  108. <H3>Reading Data From a File</H3>
  109.  
  110.  
  111. <P>Numeric data can also be easily read from a file with the buitin
  112. functions (see Section 
  113. <A HREF="rlab-ref-5.html#reading-data">Data</A>). For
  114. this example we will read a matrix stored in a text file. The
  115. <CODE>readm</CODE> function will read a text file that contains columns of
  116. numbers. In this instance the file looks like:</P>
  117. <P>
  118. <HR>
  119. <PRE>
  120.         17        24         1         8        15
  121.         23         5         7        14        16
  122.          4         6        13        20        22
  123.         10        12        19        21         3
  124.         11        18        25         2         9
  125. </PRE>
  126. <HR>
  127. </P>
  128. <P>The matrix can be read with the following statement.</P>
  129. <P>
  130. <BLOCKQUOTE><CODE>
  131. <PRE>
  132. > m = readm("magic.dat");
  133. </PRE>
  134. </CODE></BLOCKQUOTE>
  135. </P>
  136.  
  137.  
  138.  
  139. <H3>Basic Math Operations</H3>
  140.  
  141.  
  142. <P>The basic mathematical operators: <CODE>+,-,*,/</CODE> work on numeric
  143. objects of any dimension. If the operands are scalars, then the
  144. operations are performed as expected:</P>
  145. <P>
  146. <BLOCKQUOTE><CODE>
  147. <PRE>
  148. > 2 + 3
  149.         5  
  150. > 2 - 3
  151.        -1  
  152. > 2 * 3
  153.         6  
  154. > 2 / 3
  155.     0.667  
  156. </PRE>
  157. </CODE></BLOCKQUOTE>
  158. </P>
  159. <P>If either of the operands have dimensions higher than one, then
  160. array or matrix operations are performed. Array operations act in an
  161. element-by-element sense. That is, the scalar value is used
  162. repeatedley to perform the operation on each element of the
  163. array. For example:</P>
  164. <P>
  165. <BLOCKQUOTE><CODE>
  166. <PRE>
  167. > a+2
  168.         3          4          5  
  169.         6          7          8  
  170.         9         10         11  
  171. > 2*a
  172.         2          4          6  
  173.         8         10         12  
  174.        14         16         18  
  175. </PRE>
  176. </CODE></BLOCKQUOTE>
  177. </P>
  178. <P>When both operands are matrices, then matrix operations are
  179. performed, provided the dimensions of the operands are
  180. appropriate. For example:</P>
  181. <P>
  182. <BLOCKQUOTE><CODE>
  183. <PRE>
  184. > a+a
  185.         2          4          6  
  186.         8         10         12  
  187.        14         16         18  
  188. > a*a
  189.        30         36         42  
  190.        66         81         96  
  191.       102        126        150  
  192. > [1,2,3] * a
  193.        30         36         42  
  194. > a * [1;2;3]
  195.        14  
  196.        32  
  197.        50  
  198. </PRE>
  199. </CODE></BLOCKQUOTE>
  200. </P>
  201.  
  202.  
  203.  
  204. <H3>Basic Tools</H3>
  205.  
  206.  
  207. <P>In addition to the basic mathematical operators, there are many
  208. functions designed to operate efficiently on arrays. Most of the
  209. functionality these functions provide could be performed with fairly
  210. simple algorithms written in the Rlab language. However, these
  211. functions are written in the C-language (a compiled language), and
  212. are optimized for operations on arrays. Generally, using these
  213. functions will produce programs with good performance, and a minimum
  214. of effort. Generally, there are three types of functions: scalar,
  215. vector, and matrix.</P>
  216. <P>
  217. <DL>
  218. <DT><B>Scalar Functions:</B><DD><P>These functions operate on scalar
  219. values, and treat arrays (matrices) in an element-by-element
  220. fashion. For example, the function <CODE>abs</CODE> will return the
  221. absolute value of an object (provided it is a numeric
  222. object). If the object is scalar in size, the result is
  223. scalar. If the object is an array, either a vector or a matrix,
  224. then the result is the an array of the same size, with each
  225. element representing the absolute value of the corresponding
  226. element of the input array.</P>
  227.  
  228. <DT><B>Vector Functions:</B><DD><P>These functions operate on either row
  229. (1-by-N), or column (N-by-1) vectors. If the argument is an
  230. array with dimensions N-by-M, then the operation is performed
  231. on the M columns of the input.</P>
  232.  
  233. <DT><B>Matrix Functions:</B><DD><P>These function operate on matrices as a
  234. single entity. These functions may return a scalar, a vector,
  235. another matrix, or any combination. For example, the function
  236. <CODE>det</CODE> returns a scalar value, while <CODE>eig</CODE> returns a
  237. matrix (the eigenvectors), and a vector (the eigenvalues).</P>
  238. </DL>
  239. </P>
  240. <P>Using the matrices created in the previous section we will
  241. demonstrate some of the most frequently used functions.</P>
  242. <P>The matrix <CODE>m</CODE> has been termed a "magic square" matrix by
  243. some. The name is due to the properties of the matrix. First of all,
  244. its elements are integers from 1 to N squared (N is the dimension of
  245. the matrix). The sum of each row, the sum of each column, and the
  246. sum of the diagonal elements are all the same. These properties can
  247. be displayed very simply with the help of some functions.</P>
  248. <P>
  249. <BLOCKQUOTE><CODE>
  250. <PRE>
  251. > sum(m)
  252.        65         65         65         65         65  
  253. > sum(m')
  254.        65         65         65         65         65  
  255. > sum(diag(m))
  256.        65  
  257. </PRE>
  258. </CODE></BLOCKQUOTE>
  259. </P>
  260.  
  261.  
  262.  
  263. <H3>Linear Algebra</H3>
  264.  
  265.  
  266. <P>Rlab contains a high-level interfaces to the LAPACK (Linear Algebra
  267. PACKage), the FFTPACK (Fast Fourier Transform PACKage), and the
  268. RANLIB (RANdom number LIBrary) libraries. These interfaces can
  269. simplify many, otherwise difficult programming tasks. For example,
  270. we might be interested in solving a system of equations. Using the
  271. magic-square matrix once again</P>
  272. <P>
  273. <BLOCKQUOTE><CODE>
  274. <PRE>
  275. > 1/rcond(m)
  276.       6.7  
  277. > x = solve(m, ones(5,1))
  278.    0.0154  
  279.    0.0154  
  280.    0.0154  
  281.    0.0154  
  282.    0.0154  
  283. > m*x - ones(5,1)
  284.         0  
  285.         0  
  286.         0  
  287.         0  
  288.         0  
  289. </PRE>
  290. </CODE></BLOCKQUOTE>
  291. </P>
  292. <P>The function <CODE>rcond</CODE> estimates the reciprocal of the matrix
  293. condition number. A value of 6.7 indicates that the magic-square
  294. matrix is reasonably well conditioned (full-rank). Next, we use the
  295. <CODE>solve</CODE> function, to get the solution to the system of
  296. equations with coefficients of the magic-square, and right-hand
  297. sides of unity. Lastly, we check the result by mulitplying the
  298. coefficient matrix by the solution vector (<CODE>m*x</CODE>) and
  299. subtracting the right-hand side. The result should be a zero-vector
  300. (and it is).</P>
  301. <P>Note that there are other ways to solve a system of equations. The
  302. <CODE>\</CODE> operator (see Section 
  303. <A HREF="rlab-ref-3.html#arithmetic-ops">Arithmetic Operations</A>) could be used like:</P>
  304. <P>
  305. <BLOCKQUOTE><CODE>
  306. <PRE>
  307. > x = m\ones(5,1)
  308. </PRE>
  309. </CODE></BLOCKQUOTE>
  310. </P>
  311. <P>Or, the <CODE>inv</CODE> function could be used. However, using <CODE>inv</CODE>
  312. is usually a bad idea.</P>
  313. <P>In addition to the linear-algebra functions supplied to solve
  314. systems of equations, there are numerous others such as <CODE>eig</CODE>
  315. for solving eigenvalue problems, and <CODE>qr</CODE> for performing QR
  316. decomposition, and <CODE>svd</CODE> for performing the singular value
  317. decomposition. </P>
  318.  
  319.  
  320.  
  321.  
  322. <H2><A NAME="ss2.2">2.2 Computing the Mean</A></H2>
  323.  
  324.  
  325. <P>This example is fairly long, but it does cover allot of ground.  For
  326. this example it is assumed that there exist data in a file, for
  327. which you want to know some statistics. In this case, the mean or
  328. average, and the standard deviation. The file looks like:</P>
  329. <P>
  330. <BLOCKQUOTE><CODE>
  331. <PRE>
  332. 1        90
  333. 2        86
  334. 3        55
  335. 4        92
  336. 5        73
  337. 6        30
  338. </PRE>
  339. </CODE></BLOCKQUOTE>
  340.   </P>
  341. <P>The students are identified with an integer (the first column). To
  342. read this data, and compute the mean or average test score is
  343. simple. The <CODE>readm</CODE> function is used to get the data from the
  344. file. The contents of the file are read, and assigned to the matrix
  345. <CODE>grades</CODE>.</P>
  346. <P>
  347. <BLOCKQUOTE><CODE>
  348. <PRE>
  349. > grades = readm("jnk");
  350. > sum(grades)
  351.        21        426  
  352. > sum(grades[;2])/grades.nr
  353.        71  
  354. </PRE>
  355. </CODE></BLOCKQUOTE>
  356.   </P>
  357. <P>The function <CODE>sum</CODE> sums the column of a matrix, and is used
  358. here to look at the sums of both columns. However, only the average
  359. of the second column is desired. The following statement singles out
  360. the second column of <CODE>grades</CODE>, uses it as an argument to
  361. <CODE>sum</CODE>, and divides the result by the number of rows in
  362. <CODE>grades</CODE>. </P>
  363.  
  364.  
  365.  
  366. <H2><A NAME="ss2.3">2.3 Computing the Mean Again</A></H2>
  367.  
  368.  
  369. <P>A more complicated version (only at first glance) of the 
  370. problems is created when the professor wants to eliminate numeric
  371. identification of each student and use their names instead. This
  372. file consists of student's names in the first column, and grades in
  373. the second column.</P>
  374. <P>
  375. <BLOCKQUOTE><CODE>
  376. <PRE>
  377. Jeanne       90
  378. John         86
  379. Fred         55
  380. David        92
  381. Alice        73
  382. Dork         30
  383. </PRE>
  384. </CODE></BLOCKQUOTE>
  385.   </P>
  386. <P>Although the file format is simple, many programs/languages would
  387. have difficulty handling the mixture of string and numeric
  388. data. Rlab has a list-object which allows for convenient association
  389. of numeric and string data. Lists are N-dimensional arrays that are
  390. indexed associatively. With the list we can create elements that are
  391. indexed with the student's name. Each element will then contain the
  392. student's grade. For example: <CODE>grade.Alice</CODE> will contain
  393. Alice's grade of 73. First the data must be read and the array
  394. <CODE>grade</CODE> created.</P>
  395. <P>
  396. <BLOCKQUOTE><CODE>
  397. <PRE>
  398. > while((length(line = getline("mean_std.ex"))) != 0)
  399.   {
  400.     grade.[line.[1]] = line.[2];
  401.   }
  402. </PRE>
  403. </CODE></BLOCKQUOTE>
  404.   </P>
  405. <P>The previous four lines of code may look at little complex, but is
  406. really quite simple, taken one step at a time. Starting with the
  407. getline function call: </P>
  408. <P>
  409. <BLOCKQUOTE><CODE>
  410. <PRE>
  411. line = getline("mean_std.ex")
  412. </PRE>
  413. </CODE></BLOCKQUOTE>
  414.   </P>
  415. <P>The <CODE>getline</CODE> function takes a filename as argument, reads one
  416. line, and splits it into numbers and strings. The data are returned
  417. as a list, with the first element containing the data in the first
  418. field, the second element containing the data in the second field
  419. and so on. When <CODE>getline</CODE> can't read anymore information from
  420. the file it returns a list with zero length. To read from a file,
  421. until the end we use:</P>
  422. <P>
  423. <BLOCKQUOTE><CODE>
  424. <PRE>
  425. length(line = getline("mean_std.ex")) != 0
  426. </PRE>
  427. </CODE></BLOCKQUOTE>
  428.   </P>
  429. <P>inside a <CODE>while</CODE> statement. The <CODE>while</CODE> statement executes
  430. until the condition is false (zero). Thus, when the end-of-file is
  431. reached, and <CODE>getline</CODE> returns a zero-length list, the
  432. while-loop will terminate. The statement inside the while-loop:</P>
  433. <P>
  434. <BLOCKQUOTE><CODE>
  435. <PRE>
  436.     grade.[line.[1]] = line.[2];
  437. </PRE>
  438. </CODE></BLOCKQUOTE>
  439.   </P>
  440. <P>creates a list-variables named <CODE>grade</CODE>. Each element of grade
  441. is a student's grade. These elements are indexed with the student's
  442. name. Remember, <CODE>getline</CODE> returns a list containing the
  443. whitespace separated fields of each line, so: <CODE>line.[1]</CODE> is the
  444. first field, or the student's name in each line, and <CODE>line.[2]</CODE>
  445. is the second field, or the student's grade in each line. The result
  446. is a list. We can see the list indices by typing the list-variable's
  447. name at the prompt, and we can see the contents of a list element by
  448. using the appropriate list index.</P>
  449. <P>
  450. <BLOCKQUOTE><CODE>
  451. <PRE>
  452. > grade
  453.    Alice        David        Dork         Fred         Jeanne       
  454.    John         
  455. > grade.Alice
  456.        73
  457. </PRE>
  458. </CODE></BLOCKQUOTE>
  459.   </P>
  460. <P>To compute the mean value of the students grades, a simple for-loop
  461. is used to sum up the grades, prior to dividing the total by the
  462. number of students.</P>
  463. <P>
  464. <BLOCKQUOTE><CODE>
  465. <PRE>
  466. > total = 0;
  467. > for (i in members (grade))
  468.   {
  469.     total = total + grade.[i];
  470.   }
  471. > mean = total / length(grade)
  472.        71  
  473. </PRE>
  474. </CODE></BLOCKQUOTE>
  475.   </P>
  476.  
  477.  
  478.  
  479. <H2><A NAME="ss2.4">2.4 Fitting a Curve</A></H2>
  480.  
  481.  
  482. <P>It is often necessary to fit a curve to some experimental data. This
  483. is a simple matter with a high-level language. We will start by
  484. generating our own "experimental" data.</P>
  485. <P>First, set the random number generator to generate numbers from a
  486. uniform distribution, with a lower bound of -2, and an upper bound
  487. of 5.</P>
  488. <P>
  489. <BLOCKQUOTE><CODE>
  490. <PRE>
  491. > rand("uniform",-2, 5);
  492. </PRE>
  493. </CODE></BLOCKQUOTE>
  494. </P>
  495. <P>Next, generate random data with a linearly varying component.  The
  496. linearly varying component is formed, and stored in <CODE>off</CODE>. The
  497. simulated, measured data is stored in <CODE>b</CODE>.</P>
  498. <P>
  499. <BLOCKQUOTE><CODE>
  500. <PRE>
  501. > off = 0:-20:-.2;
  502. > b = ((off + 22) + rand( size(off) ));
  503. </PRE>
  504. </CODE></BLOCKQUOTE>
  505. </P>
  506. <P>Next, generate the Data matrix, <CODE>A</CODE>.</P>
  507. <P>
  508. <BLOCKQUOTE><CODE>
  509. <PRE>
  510. > m = b.n;
  511. > t = (1:m)/m;
  512. > A = [ ones(m,1), t', (t.^2)' ];
  513. </PRE>
  514. </CODE></BLOCKQUOTE>
  515. </P>
  516. <P>Now use left division (least squares) to solve for <CODE>x</CODE>.</P>
  517. <P>
  518. <BLOCKQUOTE><CODE>
  519. <PRE>
  520. > x = A\b';
  521. </PRE>
  522. </CODE></BLOCKQUOTE>
  523. </P>
  524. <P>Now, create a simple function that uses the computed parameters to
  525. make predictions. </P>
  526. <P>
  527. <HR>
  528. <PRE>
  529. ls = function(t)
  530. {
  531.   global (x)
  532.   return x[1] + x[2]*t + x[3]*t.^2;
  533. }
  534. </PRE>
  535. <HR>
  536. </P>
  537. <P>Last, plot a comparison of the original data, and the computed
  538. values. </P>
  539. <P>
  540. <BLOCKQUOTE><CODE>
  541. <PRE>
  542. > plgrid ();
  543. > pltitle ( "RLaB Least Squares Example" );
  544. > xlabel ( "Indeplendent Variable" );
  545. > ylabel ( "Deplendent Variable" );
  546. > plot( [ t; b; ls( t ) ]' );
  547. </PRE>
  548. </CODE></BLOCKQUOTE>
  549. </P>
  550. <P>Figure XX shows the
  551. output from the previous plot commands. The plot command is very
  552. simple, but a little mystifying at first. For the time being, you
  553. can ignore the <CODE>plgrid</CODE>, <CODE>pltitle</CODE>, <CODE>xlabel</CODE>, and
  554. <CODE>ylabel</CODE> statements; they merely server to add window dressing
  555. to the displayed plot. The <CODE>plot</CODE> takes a matrix as an
  556. argument, and plots columns two through the last versus the first
  557. column. So, the first column is <CODE>t</CODE>, the independent variable,
  558. The second column is <CODE>b</CODE>, the experimental data, and the last
  559. column is the result of the least-squares fit of the data. The
  560. matrix is formed by stacking the three individual row-vectors on top
  561. of one another, then transposing the entire matrix so that in the
  562. end it is a three column matrix.</P>
  563.  
  564.  
  565.  
  566.  
  567.  
  568.  
  569. <HR>
  570. <A HREF="rlab-ref-1.html"><IMG SRC="prev.gif" ALT="Previous"></A>
  571. <A HREF="rlab-ref-3.html"><IMG SRC="next.gif" ALT="Next"></A>
  572. <A HREF="rlab-ref.html#toc2"><IMG SRC="toc.gif" ALT="Contents"></A>
  573. </BODY>
  574. </HTML>
  575.