Working with Matrices |
Simple assignment statements involve an equation having the matrix name on the left side and either an expression involving other matrices or a matrix-generating function on the right 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. The following code performs these tasks:
> reset noprint; > daycost=0.30#coffee; > print "Daily totals", daycost[rowname=names format=8.2]; Daily totals DAYCOST 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.20You can calculate the weekly total cost for each person by using the matrix multiplication operator (*). First create a 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 by using subscript reduction operators.) The following code performs these tasks:
> ones={1,1,1,1,1}; > weektot=daycost*ones; > print "Weekly totals", weektot[rowname=names format=8.2]; Weekly totals WEEKTOT JENNY 3.90 LINDA 3.00 JIM 1.80 SAMUEL 6.00Finally, you can calculate the average number of cups consumed 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), by using the division operator (/) and the NCOL function. These two matrices are created separately, but the entire calculation could be done in one statement. Here is the code:
> grandtot=sum(coffee); > average=grandtot/ncol(coffee); > print "Total number of cups", grandtot,,"Daily average",average; Total number of cups GRANDTOT 49 Daily average AVERAGE 9.8
Copyright © 2009 by SAS Institute Inc., Cary, NC, USA. All rights reserved.