Lesson 12, Part 2: Matrix Extraction¶
Acknowledgements to ChatGPT
/* SAS/IML Examples: Extracting Elements from a Matrix */
Example 1¶
/* SAS/IML Examples: Extracting Elements from a Matrix */
proc iml;
/* 1. Extracting Rows – Medical Research */
x = {25 120 80,
45 130 85,
60 140 90};
selectedPatients = x[{1 3}, ];
print selectedPatients[label="Patients 1 and 3"];
quit;
| Patients 1 and 3 | ||
|---|---|---|
| 25 | 120 | 80 |
| 60 | 140 | 90 |
Example 2¶
proc iml;
/* 2. Extracting Columns – Finance */
prices = {100 105 102,
98 103 101,
97 102 100};
closing = prices[, 3];
print closing[label="Closing Prices"];
quit;
| Closing Prices |
|---|
| 102 |
| 101 |
| 100 |
Example 3¶
proc iml;
/* 3. Extracting Submatrices – Medical Imaging */
image = {50 52 54,
48 50 53,
47 49 51};
region = image[1:2, 1:2];
print region[label="2x2 Image Region"];
quit;
| 2x2 Image Region | |
|---|---|
| 50 | 52 |
| 48 | 50 |
Example 4¶
proc iml;
/* 4. Extracting Specific Elements Using Indices – Survey Analysis */
responses = {4 3 5,
2 4 3,
5 5 4};
idx = {1 3,
2 2};
scores = responses[idx];
print scores[label="Selected Scores"];
quit;
| Selected Scores |
|---|
| 4 |
| 5 |
| 3 |
| 3 |
Example 5¶
In SAS/IML, when you index a matrix with another matrix (like responses[idx]), the values in idx are interpreted linearly, i.e., as linear indices into the matrix — not as row-column pairs. So first, SAS/IML flattens the responses matrix in column-major order:
index: 1 2 3 4 5 6 7 8 9 value: 4 2 5 3 4 5 5 3 4
So, the linear indices are 1, 3, 2, and 2 → This picks:
responses[1] = 4 responses[3] = 5 responses[2] = 2 responses[2] = 2
proc iml;
/* 5. Logical Indexing – Medical Screening */
bp = {120 135 128,
142 125 110,
138 130 145};
highBP = bp[loc(bp > 130)];
print highBP[label="High Blood Pressure Values"];
quit;
| High Blood Pressure Values |
|---|
| 135 |
| 142 |
| 138 |
| 145 |
Example 6¶
proc iml;
/* 6. Submatrix Loop – Time-Series Batch Processing */
sales = {200, 210, 220, 230};
do i = 1 to nrow(sales)-1;
window = sales[i:i+1];
avg = mean(window);
print avg[label="2-Day Rolling Average"];
end;
quit;
| 2-Day Rolling Average |
|---|
| 205 |
| 2-Day Rolling Average |
|---|
| 215 |
| 2-Day Rolling Average |
|---|
| 225 |
- Defines a column vector called sales with 4 values. Think of it like this:
sales = {200, 210, 220, 230}; Think of it like this: sales = 200 210 220 230
- do i = 1 to nrow(sales)-1;
This loop goes from i = 1 to i = 3 because nrow(sales) returns 4.
We loop over the data to calculate the average of every 2-day window.
- window = sales[i:i+1];
Creates a submatrix (a slice of sales) from row i to row i+1.
i window 1 {200, 210} 2 {210, 220} 3 {220, 230}
Example 7¶
proc iml;
/* 7. Modifying Extracted Parts – Data Correction */
bp2 = {120 80,
130 0,
110 0};
zeroIdx = loc(bp2[,2]=0);
bp2[zeroIdx, 2] = 80;
print bp2[label="Corrected BP Values"];
quit;
| Corrected BP Values | |
|---|---|
| 120 | 80 |
| 130 | 80 |
| 110 | 80 |