MathGroup Archive 1996

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Setting parts of matrices

> Can somebody tell me how to set a submatrix of a larger matrix?
> Assume a is a larger matrix than b. I would like to do something
> like
>   a[[Range[i1,i2],Range[j1,j2]]]=b;
> ...
> Jens Olav Nygaard

Dear Mr. Nygaard,

Here is one solution to your problem. Evaluating

    setSubmatrix[a, b, {i1, j1}]

will reset the appropriate submatrix of a with upper left corner 
{i1, j1} to b, where the function 
setSubmatrix is defined as follows:
 SetAttributes[setSubmatrix, HoldFirst]; 
 setSubmatrix[mat_?MatrixQ, newSubmat_?MatrixQ,
                    {imin_Integer, jmin_Integer}] :=
         Hold[mat[[##]] ]&[i, j], 
         {i, imin, -1 + imin + Dimensions[newSubmat][[1]] },
         {j, jmin, -1 + jmin + Dimensions[newSubmat][[2]] } ],

For example, if you enter

    a = {{1, 2, 3}, {4, 5, 6}};
    setSubmatrix[a, {{"P"}, {"Q"}}, {1, 2}]

then the new value of a is 

    {{1, "P", 3}, {4, "Q", 6}}.

  What the function setSubmatrix does in this case is to form 
and execute the expression

    {{a[[2, 1]]}, {a[[2, 2]]}} = {{"P"}, {"Q"}}

Mathematica knows how interpret a statement like 

    a[[2, 1]] = "P"

as a request to change part 2, 1 of the value of a; and 
also how, in effect, to thread Set commands over Lists, in 
a way that is more efficient than a user-written loop. 

  Another way to solve your problem would be to use Join, 
Take, Drop and Transpose statements to write a function 
replaceSubmatrix that *returns* the result of replacing the 
appropriate submatrix of a with b. You could then type

    a = replaceSubmatrix[a, b, {i1, j1}]

to change the value of a. 


Chris Stover
crstover at

  • Prev by Date: Re: Setting parts of matrices
  • Next by Date: Mathematica Link for Microsoft Word now available
  • Previous by thread: Re: Setting parts of matrices
  • Next by thread: Re: Setting parts of matrices