MathGroup Archive 1996

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

Search the Archive

Re: addressing matrix elements

  • To: mathgroup at smc.vnet.net
  • Subject: [mg3587] Re: addressing matrix elements
  • From: wagner at bullwinkle.cs.Colorado.EDU (Dave Wagner)
  • Date: Wed, 27 Mar 1996 03:26:36 -0500
  • Organization: University of Colorado, Boulder
  • Sender: owner-wri-mathgroup at wolfram.com

In article <4itopk$v8 at dragonfly.wolfram.com>, David Cabana <drc at emi.net> wrote:
>
>More generally, I would like to be able to apply a function f to each
>element in a matrix of arbitrary size and dimensions, without worrying
>about the particulars of the matrix representation via lists.  I want
>func[M, g] to return a matrix of the same size and shape as M, with
>elements formed by applying g to corresponding elements of M.  Is there
>nice way to do this?  Seems like some combination  of Map, Apply, Thread,
>SetAttributes Listable, Outer, etc. could do the job, but I am lost in the
>morass of possibilites.   Any help would be appreciated.

Whoa, you're trying way too hard.  All you need to do is use Map with
a level specification.  The level specification you want is TensorRank[m],
which gives the number of dimensions of the matrix.  Here are some examples:

In[1]:=
    m1 = Array[a, {2,3}]
Out[1]=
    {{a[1, 1], a[1, 2], a[1, 3]}, 
      {a[2, 1], a[2, 2], a[2, 3]}}

In[2]:=
    Map[f, m1, {TensorRank[m1]}]
Out[2]=
    {{f[a[1, 1]], f[a[1, 2]], f[a[1, 3]]}, 
      {f[a[2, 1]], f[a[2, 2]], f[a[2, 3]]}}

In[3]:=
    m2 = Array[b, {2,3,2}]
Out[3]=
    {{{b[1, 1, 1], b[1, 1, 2]}, {b[1, 2, 1], b[1, 2, 2]}, 
       {b[1, 3, 1], b[1, 3, 2]}}, {{b[2, 1, 1], b[2, 1, 2]}, 
       {b[2, 2, 1], b[2, 2, 2]}, {b[2, 3, 1], b[2, 3, 2]}}}

In[4]:=
    Map[f, m2, {TensorRank[m2]}]
Out[4]=
    {{{f[b[1, 1, 1]], f[b[1, 1, 2]]}, {f[b[1, 2, 1]], f[b[1, 2, 2]]}, 
     {f[b[1, 3, 1]], f[b[1, 3, 2]]}}, {{f[b[2, 1, 1]], f[b[2, 1, 2]]}, 
     {f[b[2, 2, 1]], f[b[2, 2, 2]]}, {f[b[2, 3, 1]], f[b[2, 3, 2]]}}}

Note that my initial reaction was to use a level specification of {-1},
which means, "the lowest level".  Unfortunately, that caused this to happen:

In[3]:=
    Map[f, m1, {-1}]
Out[3]=
    {{a[f[1], f[1]], a[f[1], f[2]], a[f[1], f[3]]}, 
      {a[f[2], f[1]], a[f[2], f[2]], a[f[2], f[3]]}}

Using {-1} would work if your matrices were numeric, of course.

		Dave Wagner
		Principia Consulting
		(303) 786-8371
		dbwagner at princon.com
		http://www.princon.com/princon

==== [MESSAGE SEPARATOR] ====


  • Prev by Date: Re: addressing matrix elements
  • Next by Date: Assigning to function argument -- How to do it & Novice info
  • Previous by thread: Re: addressing matrix elements
  • Next by thread: Re: addressing matrix elements