Contributor
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??

PROC Star
Posts: 1,283

## Re: Array algebra

So you want to do this inside a data step?

Super User
Posts: 23,754

## 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.

Posts: 1,837

## 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.

https://communities.sas.com/t5/Base-SAS-Programming/Array-help/td-p/298434

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

SAS Super FREQ
Posts: 4,242

## 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) );
run;

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

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]);
end;
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.

Discussion stats
• 4 replies
• 297 views
• 1 like
• 5 in conversation