Irena
Irena

Reputation: 1

Do Loop for Matrix Multiplication in SAS

I have a 6*6 matrix called m1, and I want to use Do Loop in SAS to create matrices such that m2=m1*m1; m3=m2*m1; m4=m3*m1 ... mi=m(i-1)*m1.

Here is what I wrote:

proc iml;
use a;
read all into cat(m,1);
do i=2 to 10;
j=i-1;
cat(m,i)=cat(m,j)*cat(m,1);
print cat(m,i);
end;
quit;

And it won't work because cat(m,1) may not be correct. How can I use the Do Loop for this? Thank you very much for your time and help!

Upvotes: 0

Views: 450

Answers (2)

Rick
Rick

Reputation: 1210

For many iterative algorithms, you want to perform some computation on EACH matrix, but you don't need all matrices at the same time. For example, if you wanted to know the determinant of m, m##2, m##2, etc, you would write

result = j(10,1);  /* store the 10 results */
m = I(nrow(a));    /* identity matrix */
do i = 1 to 10;
   m = m*a;        /* m is a##i during i_th iteration */
   result[i] = det(m);
end;
print result;

If you actually need all 10 matrices at the same time in different matrices (this is rare), you can use the VALSET and VALUE functions as explained in this article: Indirect assignment: How to create and use matrices named x1, x2,..., xn

As an aside, you might also be interested in the trick of packing matries into an array by flattening them. It is sometimes a useful technique when you need to return k matrices from function module and k is a parameter to the module.

Upvotes: 0

DomPazz
DomPazz

Reputation: 12465

cat() is not going to work. It is a character function. It is not going to create a matrix named by the string output.

Why not just use the matrix power operator?

m2 = m1**2;
m3 = m1**3;

Unless you have big matrices, the time saved iterating the calculation instead of just using the power is next to 0.

Upvotes: 1

Related Questions