comp.lang.idl-pvwave archive
Messages from Usenet group comp.lang.idl-pvwave, compiled by Paulo Penteado

Home » Public Forums » archive » Swap even/odd elements in array
Show: Today's Messages :: Show Polls :: Message Navigator
E-mail to friend 
Return to the default flat view Create a new topic Submit Reply
Re: Swap even/odd elements in array [message #44553 is a reply to message #44507] Tue, 28 June 2005 12:00 Go to previous messageGo to previous message
JD Smith is currently offline  JD Smith
Messages: 850
Registered: December 1999
Senior Member
On Wed, 22 Jun 2005 10:52:04 +0200, Xavier Llobet wrote:

> In article <1119428174.330105.170110@o13g2000cwo.googlegroups.com>,
> photosalex@freenetname.co.uk wrote:
>
>> Hi All,
>> sorry if the question is trivial:
>> how could I swap even and odd elements of a 1-D 16-bit INT array
>> without using loops? That is, if the source array is
>>
>> [a0,a1,a2,a3,..]
>>
>> I want it to be
>>
>> [a1,a0,a3,a2,..]
>>
>> Thanks!
>
> n = (size(a))(1)
> ind=2*indgen(n)
> b=reform(transpose(reform([a(ind+1),a(ind)],n/2,2)),n)


A similar approach using the new stride indexing operator would be:

b=reform(transpose([[a[1:*:2]],[a[0:*:2]]]),n_elements(a))

The problem with all of these dimensional-juggling approaches is that
they fail for vectors of odd length (or, more generally, require the
length be a strict multiple of p, where p is the transposition length).

Here's a method which doesn't have this requirement:

ind=lindgen(n_elements(a))/2*2 & ind[0:*:2]+=1
b=a[ind]

It can be generalized for any p like this:

ind=lindgen(n_elements(a))/p*p
for i=0,p-2 do ind[i:*:p]+=p-1-i
b=a[ind]

It does require the vector to have at least p-1 elements.

JD
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Histogram shift
Next Topic: background transparency in tvscl?

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ] [ PDF ]

Current Time: Sat Oct 11 15:31:07 PDT 2025

Total time taken to generate the page: 0.23733 seconds