[Date Index]
[Thread Index]
[Author Index]
Re: MapThread over ragged arrays
*To*: mathgroup at smc.vnet.net
*Subject*: [mg83419] Re: MapThread over ragged arrays
*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
*Date*: Tue, 20 Nov 2007 03:46:47 -0500 (EST)
*Organization*: The Open University, Milton Keynes, UK
*References*: <fhrrbf$583$1@smc.vnet.net>
Ravi Balasubramanian wrote:
> I have two matrices that are ragged.
Note that matrices, as defined in linear algebra, are never ragged: they
always have a regular shape (rectangular or square). An array can be
ragged, however.
> mat1 = {{1, 2}, {2, 3, 4}, {5, 6}}
> mat2 = {{a, b}, {b, c, d}, {e, f}}
>
> I have to Map a function f at level 2. So that I have
>
> {
> {f[1,a],f[2,b]},
> {f[2,b], f[3,c], f[4,d]},
> {f[5,e],f[6,f]},
> }
>
> MapThread seems to thread only over full arrays, and so I cannot thread
(* Rant *)
Buried in the abysses of the help page for MapThread under the title
"Possible Issues" within the "Examples" section, the adventurous mind
can read, "All arguments must be lists of the same length." Usually,
possible issues refer to some specific or exceptional cases, whereas, in
this case, the restriction is by design: it is mandatory to pass lists
of equal length. Sometimes I really wonder who wrote the documentation
of version 6 :-)]
(* End Rant *)
> over level {2}. I know I can I do this using two MapThreads (each at
> level 1), but that seems unnecessary. Thread seems to apply the head to
> each value, and if the head does not match, the value is repeated (which
> might not be necessary). Seems like a simple thing to do. Any ideas?
The following should do what you are looking for. The function pad, a
helper function, reshapes a ragged array into a rectangular structure,
padding the extra elements with Sequence. We call MapThread with the
padded arrays and the successive application of the transformation rules
Sequence -> Sequence[] and f[] -> Sequence[] reconstructs an array with
a shape identical to the original ragged arrays.
In[1]:= pad[lst_List] := PadRight[#, Length@lst, Sequence] & /@ lst
rag1 = {{1, 2}, {2, 3, 4}, {5, 6}};
rag2 = {{a, b}, {b, c, d}, {e, f}};
MapThread[f, pad /@ {rag1, rag2}, 2] /. Sequence -> Sequence[] /.
f[] -> Sequence[]
Out[4]= {{f[1, a], f[2, b]}, {f[2, b], f[3, c], f[4, d]}, {f[5, e],
f[6, f]}}
Regards,
--
Jean-Marc
Prev by Date:
**Re: Plot to Plot3D problem**
Next by Date:
**Re: ordered positions (OrderedPosition?)**
Previous by thread:
**Re: MapThread over ragged arrays**
Next by thread:
**Re: MapThread over ragged arrays**
| |