BookmarkSubscribeRSS Feed
deleted_user
Not applicable
Hello, I hope all is well. I am trying to calculate a mean and standard deviation of elements in a matrix (that is the mean (and std) of all elements in a matrix), but cannot figure out if syntax exists within PROC IML. If a matrix 3x3 matrix has 9 elements (numbered 1-9) then the mean of the matrix is 5. I've tried a lot of options, but can't get it to work.

The backstory is that I need to translate MATLAB (which I don't have access to) code into IML, but again, can't find comparable functions. For example, for a matrix g, the MATLAB code for std is std(g(:)) and the code for mean is mean(mean(g).

Thank you for any assistance. Take care.

Todd
3 REPLIES 3
Olivier
Pyrite | Level 9
Hi Todd.
Since IML is part of SAS, it does not expect roxs and columns to be part of the same data series. So there seems to be nothing as simple as in Matlab to compute such means and standard deviations ; it would have been done with the MEAN and STD functions if your data were arranged as {1 2 3 4 5 6 7 8 9}, in one row or one column only.
Here are workarounds to compute means & standard deviations for a whole matrix.
[pre]
PROC IML ;
a = {1 2 3 4, 5 6 7 8, 9 10 11 12} ;
mean = a[+,+]/(NROW(a)*NCOL(a)) ;
PRINT mean ;
std = SQRT((a-mean)[##,+]/(NROW(a)*NCOL(a)-1)) ;
PRINT std ;
QUIT ;
[/pre]
Regards.
Olivier

PS : the + and ## syntax is taken from the Example 8.1 in the SAS IML documentation (General Statistics > Correlation).
Rick_SAS
SAS Super FREQ
You can use A[:] for the mean and M[##] for sum of squares of a matrix.
If you have missing values, then you need to be careful about the divisor for the standard deviation. Try the following:
proc iml;
a = {. 2 3 4, 5 6 . 8, 9 10 11 12} ;
mean = a[:];
numNonMissing = ncol(loc(a^=.));
std = sqrt( (a-mean)[##] / (numNonMissing-1) );
print mean std;

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 8694 views
  • 0 likes
  • 3 in conversation