Chapter Contents
Chapter Contents
Working with Matrices

Simple Assignment Statements

Simple assignment statements involve an equation having the matrix name on the left-hand side and either an expression involving other matrices or a matrix-generating function on the right-hand side.

Suppose you want to generate some statistics for the weekly coffee data. If a cup of coffee costs 30 cents, then you can create a matrix with the daily expenses, DAYCOST, by multiplying the per-cup cost with the matrix COFFEE using the elementwise multiplication operator (#). Turn off the automatic printing so that you can tailor the output with the ROWNAME= and FORMAT= options in the PRINT statement.

   >  reset noprint;
   >  daycost=0.30#coffee;
   >  print "Daily totals", daycost[rowname=names format=8.2];

           Daily totals

           JENNY       1.20     0.60     0.60     0.90     0.60
           LINDA       0.90     0.90     0.30     0.60     0.30
           JIM         0.60     0.30     0.00     0.60     0.30
           SAMUEL      1.50     1.20     1.20     0.90     1.20
You can calculate the weekly total cost for each person using the matrix multiplication operator (*). First create a 5 ×1 vector of 1s. This vector sums the daily costs for each person when multiplied with COFFEE. (You will see later that there is a more efficient way to do this using subscript reduction operators.)
   >  ones={1,1,1,1,1};
   >  weektot=daycost*ones;
   >  print "Week total", weektot[rowname=names format=8.2];

                Week total

                JENNY       3.90
                LINDA       3.00
                JIM         1.80
                SAMUEL      6.00
Finally, you can calculate the average number of cups drunk per day by dividing the grand total of cups by days. To find the grand total, use the SUM function, which returns the sum of all elements of a matrix. Next, divide the grand total by 5, the number of days (which is the number of columns) using the division operator (/) and the NCOL function. These two matrices are created separately, but the entire calculation could be done in one statement.
   >  grandtot=sum(coffee);
   >  average=grandtot/ncol(coffee);
   >  print "Total number of cups", grandtot,,"Daily average",average;

                        Total number of cups


                           Daily average


Chapter Contents
Chapter Contents

Copyright © 1999 by SAS Institute Inc., Cary, NC, USA. All rights reserved.