```Date: Sat, 10 Oct 2009 10:55:03 -0400 Reply-To: Muthia Kachirayan Sender: "SAS(r) Discussion" From: Muthia Kachirayan Subject: Re: matrix mulitplication................... Comments: cc: gupt In-Reply-To: Content-Type: text/plain; charset=ISO-8859-1 On Fri, Oct 9, 2009 at 2:15 AM, gupt wrote: > Hi, > I am having one doubt can we do matrix multiplication by using sas. I > think we have to follow arrays concept. suppose I am having the data > sets like the following. > > data set name: first > column names : A B > > A B > 1 2 > 3 4 > > another data set name : second > column names : C D > > C D > 4 5 > 6 7 > > I want to get the output like the following > data set name : Mulitiply_first_second > column names : E F > E F > 16 19 > 36 43 > > In the final data set i need to get the matrix mulitplication......... > If anybody help me to get the above code it will be very useful to > me...... > Gupta, Matrix Multiplication through SAS datastep can be done - only we need imagination. Let us take a very general situation of two matrices with sizes 2 by 3 and 3 by 3 to yield a product matrix of 2 by 3. Dataset ONE has 2 rows and 3 columns and TWO has 3 rows and 3 columns. data one; input a b c; cards; 1 0 3 2 -1 -2 ; run; data two; input d e f; cards; -2 4 2 1 0 0 -1 1 -1 ; run; The datastep takes one row of ONE and builds up sums of products by cycling through all rows of TWO using relevant elements. The cycling of TWO requires the use of POINT option in SET statement. data mult; array prod[*] p1 p2 p3; set one; array k[*] a b c; *** Vars of dataset ONE; i = 0; do row = 1 to n; *** Loop through all rows of TWO; set two nobs = n point = row; array m[*] d e f; *** Vars of dataset TWO; i + 1; do j = 1 to dim(m); prod[j] = sum(prod[j], k[i] * m[j]); end; end; output; call missing(of prod[*]); keep p:; run; It will far easy to do this or any complicated matrix operations by the use of user- definable Function Compiler facility in SAS 9. Here goes. proc fcmp; array X[2,3]/nosymbols; array Y[3,3]/nosymbols; array result[2,3]; rc = read_array('one',X); rc = read_array('two',Y); call mult(X, Y, result); rc = write_array('mult', result); quit; Enough temporary array space is declared to save the datasets. ONE goes to array X and TWO goes to Y. READ_ARRAY() translates the datasets to arrays and similarly WRITE_ARRAY() does the reverse into MULT from RESULT array. Call mult() is a SAS built-in matrix multiplication function. The output of RESULT : Obs result1 result2 result3 1 -5 7 -1 2 -3 6 6 Do you find this useful? Kind regards. Muthia Kachirayan ```

Back to: Top of message | Previous page | Main SAS-L page