Re: Help with matrix operations [message #952 is a reply to message #846] |
Wed, 28 April 1993 04:47   |
zawodny
Messages: 121 Registered: August 1992
|
Senior Member |
|
|
In article <1rk7gs$4m6@morrow.stanford.edu> pln@egret0.Stanford.EDU writes:
> I have a little matrix problem that I'm trying to do without using
> loops. So far I'm not clever enough to figure out how to do it.
> Suppose we have
> A = fltarr(N,N)
> B = fltarr(N)
> C = fltarr(N,N,N)
> I want to have C(i,j,k) = A(i,j) + B(k)
> for all i,j,k < N. Is there a way to do this without writing
> ugly loops? I'm sure it's trivial, and I'll feel like a dope
> when the first person points it out. Fire away.
>
> --
> * Patrick L. Nolan (415)723-0133 *
> * W. W. Hansen Experimental Physics Laboratory (HEPL) *
> * Stanford University *
> * Bitnet: PLN@SLACVM Internet: pln@egret0.stanford.edu *
Some one has suggested what may probably be the best (fastest) way to do this:
for k=0,n-1 do a(0,0,k) = a(*,*) * b(k) .
However there is a way to do this without loops. Let's take a more general
situation. Let
A = FLTARR(x,y)
B = FLTARR(z)
C = FLTARR(x,y,z)
to get C(i,j,k) = A(i,j) * b(k) do the following ( make sure you are doing
integer math here).
; Make the indicies
ma = LINDGEN(x,y,z) mod (x*y)
mb = LINDGEN(x,y,z) / (x*y)
; define the destination array
c = fltarr(x,y,z)
; DO IT!
c(*) = a(ma(*)) * b(mb(*))
That is all there is to it. I'll argue that you have done way too much math
this way then you would have done with the signle loop idea. Some may agrue
that the use of LINDGEN is an implicit loop. I won't argue with that either.
--
Joseph M. Zawodny (KO4LW) NASA Langley Research Center
Internet: zawodny@arbd0.larc.nasa.gov MS-475, Hampton VA, 23681-0001
Packet: ko4lw@wb0tax.va.usa
|
|
|