souravsarkar59
souravsarkar59

Reputation: 127

how to multiply each row with each row of another matrix elementwise in sas?

I have a row matrix (vector) A and another square matrix B. How can I multiply each row of matrix B with the row matrix A in SAS using proc iml or otherwise?

Let's say

a = {1 2 3}
b =
{2 3 4
1 5 3
5 9 10}

My output c would be:

{2 6 12
1 10 9
5 18 30}

Thanks!

Upvotes: 2

Views: 689

Answers (2)

Joe
Joe

Reputation: 63424

There's of course a non-IML solution, or twenty, though IML as Dom notes is probably easiest. Here's two.

First, get them onto one dataset, where the a dataset is on every row (with some other variable names) - see below. Then, either just do the math (use arrays) or use PROC MEANS or similar to use the a dataset as weights.

data a;
  input w_x w_y w_z;
  datalines;
1 2 3
;;;;
run;

data b;
  input x y z;
  id=_n_;
  datalines;
2 3 4
1 5 3
5 9 10
;;;;
run;

data b_a;
  if _n_=1 then set a;
  set b;
  *you could just multiply things here if you wanted;
run;


proc means data=b_a;
class id;
types id;
var x/weight=w_x;
var y/weight=w_y;
var z/weight=w_z;
output out=want sum=;
run;

Upvotes: 0

DomPazz
DomPazz

Reputation: 12465

Use the element-wise multiplication operator, # in IML:

proc iml;
a = {1 2 3};
b = {2 3 4, 
     1 5 3,
     5 9 10};

c = a#b;
print c;
quit;

Upvotes: 3

Related Questions