Re: addressing matrix elements
- To: mathgroup at smc.vnet.net
- Subject: [mg3619] Re: [mg3566] addressing matrix elements
- From: Richard Mercer <richard at seuss.math.wright.edu>
- Date: Thu, 28 Mar 1996 00:11:50 -0500
- Sender: owner-wri-mathgroup at wolfram.com
> The Mma language sometimes drives me crazy. If I don't > practice it regularly, I seem to forget everything. > Here's what I want to do, but can't. > > 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. For instance, func[{{22,33}, {44,55}}, 10] should > return {{2,3}, {4,5}}. I would like this to work for > arbitrary rectangular integer matrices, but am not having > much luck. It seems like this should be easy, but I'm > stumped. > > 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. > > Thanks, > > -- David Cabana drc at gate.net > Here is one semi-elegant way: Attributes[ModAll] = {Listable}; ModAll[m_,n_]:= Mod[m,n]; Then use it as follows list = {34,{56,82},{90,25,{61,77}}}; ModAll[list,7] {6, {0, 5}, {6, 4, {5, 0}}} You could alternatively Unprotect[Mod] SetAttributes[Mod,Listable] and then Mod itself would behave in the desired fashion. I prefer the former method as it does not alter the original Mod. If you feel that using the Listable attribute is "cheating" (I don't know why), another alternative is ModAll[ls_List,n_]:= ModAll[#,n]& /@ ls; ModAll[m_,n_]:= Mod[m,n]; Richard Mercer ==== [MESSAGE SEPARATOR] ====