Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

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

Search the Archive

Re: Threading over matrices

  • To: mathgroup at smc.vnet.net
  • Subject: [mg90762] Re: Threading over matrices
  • From: Alberto Verga <Alberto.Verga at laposte.net>
  • Date: Wed, 23 Jul 2008 05:58:15 -0400 (EDT)
  • References: <g64487$djo$1@smc.vnet.net>

Hi,
You may try MapThread[]

For example:

Create the data
x = RandomReal[{0, 1}, {3, 4}]
y = RandomReal[{0, 1}, {3, 4}]

{{0.0617457, 0.895605, 0.766934, 0.0769308}, {0.226479,
  0.0894829, 0.563185, 0.789292}, {0.0419649, 0.823764, 0.597748,
  0.513526}}
{{0.610528, 0.955936, 0.999041, 0.0561156}, {0.59444,
  0.375375, 0.659419, 0.205936}, {0.278044, 0.874925, 0.532864,
  0.799205}}

Define the desired function f,
f = If[#1 > #2, 1/#1, #1 - #2] &

Use MapThread to apply f to each pair {x(i,j),y(i,j)} of numvers:
MapThread[f, {x, y}, 2]

You get the matrix:
{{-0.548783, -0.0603309, -0.232108,
  12.9987}, {-0.367961, -0.285892, -0.0962331,
  1.26696}, {-0.236079, -0.0511604, 1.67295, -0.285678}}

Alberto Verga

"<\"@frank-exchange-of-views.oucs.ox.ac.uk" <"Robert> wrote:
> How can I get evaluations to thread over matrices with
> conditional functions?
> Here's examples that show the behaviour that's really
> frustrating me.
> Create a couple of matrices:
>
> x = Table[Random[],{3},{4}];
> y = Table[Random[],{3},{4}];
> a=0.5;
>
> (These are example values I would like the following
> to apply to lists of any dimension.)
> When you add them they create a result with the same
> dimensions where each element corresponds to the
> input elements
>
> x + a y
>
> And some functions do similar
>
> Cos[x] + Sin[a y]
>
> But some don't, e.g.
>
> x > y
> x > a
>
> I would have liked those to produce a matrix of corresponding
> True and False results, and then something like:
>
> If[x > y, 1/x, x - y]
> Piecewise[{{1,x==a},{x^2,x>a}},x y^2]
>
> to produce a matrix of results corresponding to each element.
>
> They don't - I haven't managed to find out why they don't or
> more usefully how to do what I would like them to do.
>
> I have searched Help on all the likely commands (I think: Map,
> Thread, Apply, Distribute, ...) and this archive, where there
> are similar enquiries but none that match.  Perhaps I'm looking
> in the wrong place - I expect there's someone who can help.
>
> Robert


  • Prev by Date: Can't integrate sqrt(a+b*cos(t)+c*cos(2t))
  • Next by Date: Re: Threading over matrices
  • Previous by thread: Re: Threading over matrices
  • Next by thread: Re: Threading over matrices