Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2009

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

Search the Archive

Re: Assign new values to matrix using indices

  • To: mathgroup at smc.vnet.net
  • Subject: [mg99780] Re: Assign new values to matrix using indices
  • From: Malcolm <mwjdavidson at googlemail.com>
  • Date: Thu, 14 May 2009 01:41:41 -0400 (EDT)
  • References: <gue2k2$7ll$1@smc.vnet.net> <gue6rp$b7s$1@smc.vnet.net>

The solution from Jens has the merit of being relatively short and
clear. However it makes use of If statements to identify lower
triangular matrix elements. Assuming that we would like to use any set
of indices (e.g. derived from alternate criteria) and, thinking about
it a little more, a general method for such assignments could  be the
following.

In[38]:= m = {{a, b, c}, {d, e, f}, {h, i, j}};
ind = {{2, 1}, {3, 1}, {3, 2}};
Scan[Set[m[[#[[1]], #[[2]]]], m[[#[[1]], #[[2]]]]/2] &, ind]
m

Out[41]= {{a, b, c}, {d/2, e, f}, {h/2, i/2, j}}

Mac

On May 13, 12:19 pm, Jens-Peer Kuska <ku... at informatik.uni-leipzig.de>
wrote:
> Hi,
>
> with
>
> m = {{a, b, c}, {d, e, f}, {h, i, j}};
>
> try
>
> MapIndexed[If[Greater @@ #2, #1/2, #1] &, m, {2}]
>
> Regards
>    Jens
>
> Mac wrote:
> > This simple problem has got me confounded (despite 2 years of
> > Mathematica experience). Say I would like to divide all lower diagonal
> > elements of a matrix by 2. It is fairly easy to generate a list of
> > indices, here an example for 3 by 3 matrix
>
> > In[120]:=
> > Table[{j, i}, {j, 2, cdim = 3}, {i, 1, j - 1}] // Flatten[#, 1] &
>
> > Out[120]= {{2, 1}, {3, 1}, {3, 2}}
>
> > Now if I would like to divide the elements of a 3 x 3 matrix by 2, I
> > don't know how to do this. The problem is the complex interplay of Part
> > [], Set[] and Apply[]. To set the elements of hte matrix I can do
> > this
>
> > In[219]:= t2 = {{0, 0, 0}, {2, 0, 0}, {2, 2, 0}};
> > f = Function[{x}, Apply[Set[Part[t2, ##], 1] &, x]];
> > Scan[f, {{2, 1}, {3, 1}, {3, 2}}]
> > t2
>
> > Out[222]= {{0, 0, 0}, {1, 0, 0}, {1, 1, 0}}
>
> > which seems complicated for a simple operation. However, to divide all
> > elements with indices given in the form above i.e. {{2, 1}, {3, 1},
> > {3, 2}} by 2 has got me stumped.
>
> > Any help would be appreciated
>
> > Mac



  • Prev by Date: Re: Re: Assign new values to matrix using indices
  • Next by Date: Re: Re: second simple problem
  • Previous by thread: Re: Assign new values to matrix using indices
  • Next by thread: Re: Introducing the Wolfram Mathematica Tutorial