|
Re: Adding arrays of different dimensions [message #56429 is a reply to message #56427] |
Fri, 19 October 2007 10:17  |
Jean H.
Messages: 472 Registered: July 2006
|
Senior Member |
|
|
ianpaul.freeley@gmail.com wrote:
> I keep running into this and not being sure what the best solution is.
>
> I have a 2d array, and I'd like to add a 1d array to each row (or
> column).
> The easy stupid slow way:
> a=findgen(3,5)
> b=[1,2,3]
> for i=0,4 do a[*,i]=a[*,i]+b
>
> Perhaps a better way with no loops:
> a=findgen(3,5)
> b=[1,2,3]
> x=b#(fltarr(n_elements(a[0,*])) +1)
> a=a+x
>
> Is there a better way? Anyone care to generalize so I can optimally
> add 2d arrays into 3d?
>
>
> Thanks,
> IP Freeley
Xsize = 2
Ysize = 3
Zsize = 4
a = indgen(Xsize, Ysize)
b = indgen(Xsize) + 1
print, a + rebin(b,Xsize, Ysize)
or in 3D:
a = indgen(Xsize, Ysize,Zsize)
b = indgen(Xsize,Ysize) + 1
print, a + rebin(b,Xsize, Ysize,Zsize)
|
|
|
Re: Adding arrays of different dimensions [message #56430 is a reply to message #56429] |
Fri, 19 October 2007 10:07  |
David Fanning
Messages: 11724 Registered: August 2001
|
Senior Member |
|
|
ianpaul.freeley@gmail.com writes:
> I keep running into this and not being sure what the best solution is.
>
> I have a 2d array, and I'd like to add a 1d array to each row (or
> column).
> The easy stupid slow way:
> a=findgen(3,5)
> b=[1,2,3]
> for i=0,4 do a[*,i]=a[*,i]+b
>
> Perhaps a better way with no loops:
> a=findgen(3,5)
> b=[1,2,3]
> x=b#(fltarr(n_elements(a[0,*])) +1)
> a=a+x
>
> Is there a better way? Anyone care to generalize so I can optimally
> add 2d arrays into 3d?
I think a careful look at the array concatenation tutorial
would be helpful:
http://www.dfanning.com/tips/array_concatenation.html
Cheers,
David
--
David Fanning, Ph.D.
Fanning Software Consulting, Inc.
Coyote's Guide to IDL Programming: http://www.dfanning.com/
Sepore ma de ni thui. ("Perhaps thou speakest truth.")
|
|
|