DATA Step, Macro, Functions and more

Array algebra

Posts: 24

Array algebra

how can I write a simple code for array (matrix) algebra, this are my input information

y and yhat are the arrays with one column and "n" observation 
the process is repeating k times ( i = 1,...k) and for each run we have different y & yhat, 
for each run the "mean absolute difference" between y & yhat should save in "m".

m{i} = sum(of abs(y - yhat));

I don't want to use any proc, how can I write a simple code??

Posts: 552

Re: Array algebra

So you want to do this inside a data step? Smiley Happy

Super User
Posts: 17,907

Re: Array algebra

If you want to do matrix calculations your best off switching to SAS IML. 


But you really haven't told us much. Depending on your data a simple datastep may also suffice. Please post sample data and expected output if you want sample code. 

Trusted Advisor
Posts: 1,400

Re: Array algebra

If you have any sample data, look at next link and try to create any initial code that might do what you want.

If you have difficulties, post your code to the forum and you will get help.


Treat this link as a demo for how to write a data step and how to define and use arrays in sas.

Posts: 3,483

Re: Array algebra

For the DATA step solution, sort by the grouping variable and use a BY statement to accumulate the absolute residuals.


Since you mentioned matrix algebra, I'll give a SAS/IML solution, which uses the UNIQUE-LOC technique to loop over the groups:


proc glm data=sashelp.class plots=none;
class sex;
model weight = height;
output predicted=yhat out=have(rename=(weight=y sex=grp) ); 

proc iml;
use have;
read all var {grp y yhat};

r = abs(y-yhat);
u = unique(grp);
sum  = j(1, ncol(u));
do i = 1 to ncol(u);
   idx = loc(grp = u[i]);
   sum[i] = sum(r[idx]);
print sum[colname=u];

If you have huge data or many groups, it is more efficient to use the UNIQUEBY tecnique to loop over the groups.


Ask a Question
Discussion stats
  • 4 replies
  • 1 like
  • 5 in conversation