       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:=
m1 = Array[a, {2,3}]
Out=
{{a[1, 1], a[1, 2], a[1, 3]},
{a[2, 1], a[2, 2], a[2, 3]}}

In:=
Map[f, m1, {TensorRank[m1]}]
Out=
{{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:=
m2 = Array[b, {2,3,2}]
Out=
{{{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:=
Map[f, m2, {TensorRank[m2]}]
Out=
{{{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:=
Map[f, m1, {-1}]
Out=
{{a[f, f], a[f, f], a[f, f]},
{a[f, f], a[f, f], a[f, f]}}

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