Re: addressing matrix elements
- To: mathgroup at smc.vnet.net
- Subject: [mg3582] Re: addressing matrix elements
- From: cstover at mason2.gmu.edu (Christopher R Stover)
- Date: Wed, 27 Mar 1996 03:25:43 -0500
- Organization: George Mason University, Fairfax, Virginia, USA
- Sender: owner-wri-mathgroup at wolfram.com
> Say M is a matrix of integers. I want to func[M, k] to return a matrix
> same dimensions as M, each entry consisting of the corresponding entry of
> M taken modulo k.
> ...
> 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.
Dear David,
The answer to your specific question is easy because the function Mod has
Attribute Listable. Thus, if M is a matrix, the expression
Mod[M, k]
will evaluate to M with its entries reduced modulo k. This works for
vectors or deeper tensors as well.
For your more general question, if you know that M is an m x n matrix so
that all elements are two levels deep, then
Map[g, M, {2}]
will apply the function g to every element of M. If you want a
non-listable function to be threaded over lists as if it were listable,
you can make the following definition:
listThread[expr_, func_] :=
Module[{foo},
SetAttributes[foo, Listable];
foo[expr] /. foo -> func
]
Typing listThread[expr, func] will effectively thread func over any
lists in expr and return the result.
Sincerely,
Chris Stover cstover at gmu.edu
==== [MESSAGE SEPARATOR] ====