Set submatrix values within a matrixI have a matrix of missing values, and I want to set the upper left portion of that matrix to values in another matrix.
initial_matrix=J(3,3,.);
update_matrix=[1 2, 3 4];
The desired result is
[
1 2 .,
3 4 .,
. . .
]
I know I could iterate on the indices of the matrix like this
for(i=1, i<=N rows(update_matrix), i++,
for(k=1, k<=N cols(update_matrix), k++,
initial_matrix[i,k]=update_matrix[i,k]
)
);
Show(initial_matrix)
but is there an easier more compact way to do this using direct referencing of the matrix indices?
Automation and ScriptingRe: Set submatrix values within a matrixHi @MathStatChem ,
This might not be as elegant as what you're hoping for, but it should do it:
initial_matrix = J(3,3,.);
update_matrix=[1 2, 3 4];
initial_matrix[1,1::2]=update_matrix[1,1::2];
initial_matrix[2,1::2]=update_matrix[2,1::2];
Which gives you the following output:
[1 2 .,
3 4 .,
. . .]
I believe this is what you might be looking for. The indexing goes [row,n1::n2], so [1,1::2] is row 1 elements 1 to 2. The only drawback is that you have to know what submatrix you're assigning the values to ahead of time. If you don't know that information, your loop would be a better approach.
Hope this helps!,
DS
Re: Set submatrix values within a matrixThis should work for you. The Try() will simply not assign anything if the update matrix doesn't contain the row and column.
Names Default To Here( 1 );
im = J( 3, 3, . );
um = [1 2, 3 4];
im = Transform Each( {e, {r, c}}, im, Try( um[r, c] ) );
//// [1 2 .,
//// 3 4 .,
//// . . .]Re: Set submatrix values within a matrixm = j(7,8,99);
m[2::5,3::4] = [
41 42,
43 44,
45 46,
47 48
];
show(m)
m =
[ 99 99 99 99 99 99 99 99,
99 99 41 42 99 99 99 99,
99 99 43 44 99 99 99 99,
99 99 45 46 99 99 99 99,
99 99 47 48 99 99 99 99,
99 99 99 99 99 99 99 99,
99 99 99 99 99 99 99 99];
Re: Set submatrix values within a matrixThanks @Craige_Hales , that's what I was looking for. To make it more general, here is what I am doing
m=J(7,8,99);
update=[41 42,
43 44,
45 46,
47 48
];
m[1::nrows(update), 1::ncols(update)]=update;
show(m);
result
m =
[ 41 42 99 99 99 99 99 99,
43 44 99 99 99 99 99 99,
45 46 99 99 99 99 99 99,
47 48 99 99 99 99 99 99,
99 99 99 99 99 99 99 99,
99 99 99 99 99 99 99 99,
99 99 99 99 99 99 99 99];
Re: Set submatrix values within a matrixThanks. I've never used Transform Each( ), look pretty useful, and would not of thought using that on a matrix.
Re: Set submatrix values within a matrixMy code should be changed just a bit. The way it's written, any row/column combination not in the update matrix will replace the value in the initial matrix with a missing value. The Try() should have a Catch Expression to prevent overwriting the value, in case the original value isn't missing.
Names Default To Here( 1 );
im = J( 3, 3, 5 );
um = [1 2, 3 4];
im = Transform Each( {e, {r, c}}, im, Try( um[r, c], e ) );