필터 지우기
필터 지우기

How to sort even and odds elements in an array or vector recursively?

조회 수: 1 (최근 30일)
sachin gawande
sachin gawande 2014년 10월 22일
편집: Julia 2014년 10월 23일
Hi,
I am trying to sort an array of 1xN in different odd and even arrays till the length last array =4 for example: X=1:32; N=length(X) m=log2(N);
for i=1:m
A=X(1,1:2:end); %for odd bits B=X(1,2:2:end); %for even bits X=A;
if l=4 break end
a=B(1,1:2:end); %for odd bits b=B(1,2:2:end); %for even bits B=a; end
i m getting output for X=1:16 but if I increase length of X to N then its is not working; for X=1:32, I am getting only odd values
i want the o/p as [1 9 17 25 5 13 21 29 3 11 19 27 7 15 23 31 2 10 18 26 6 14 22 30 4 12 20 28 8 16 24 32]
In my code it is considering odd bits only. I want to do this for N bit but my loop is not working in that case. Please help me out
Thanks in advance

채택된 답변

Julia
Julia 2014년 10월 22일
Hi,
I don't really get your intention. What are A, B, a and b for?
And where do you compute l for the if-statement?
It would be helpful if you edited your code.
  댓글 수: 2
sachin gawande
sachin gawande 2014년 10월 22일
Actually I am trying t store array in A and B
here is my code for 16 bits but I want to generalize it for N bits, in this code if i put X =1:32 i am getting only odd integers in fact I want all integers.
clc clear all X=[1:16];
N=length(X); m=log2(N)
for i=1:m
A=X(1,1:2:end) % for odd bits
B=X(1,2:2:end)% for even bits
X=A;
l=length (X);
if l==4
break
end
a=B(1,1:2:end) % for odd bits
b=B(1,2:2:end)% for even bits
B=a;
end
[A B a b]
u can try this code you will understand what exactly A B a b are?
Julia
Julia 2014년 10월 23일
편집: Julia 2014년 10월 23일
I think I know what the problem is.
For
X = 1:16
You compute A ans B twice but a and b only once, so you keep your even values in a and b.
But for
X = 1:32
you compute A, B, a and b twice. The second time you compute a and b you use B, which now contains only odd values --> a and b now contain only odd values.
B=a
is overwritten in the next loop iteration by
B=X(1,2:2:end)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by