필터 지우기
필터 지우기

Recursively reversing large vector efficiently

조회 수: 4 (최근 30일)
Rayyan Ramrajkar
Rayyan Ramrajkar 2021년 8월 12일
댓글: Rayyan Ramrajkar 2021년 8월 14일
I am trying to write a code that will recursively compute reverse of given large vector . I have tried 2 codes one simple recursive code and other one iterative reversal code which flips 2 elements in one loop hence efficient
I want to replicate second code below in recursive way how can I approach that? Thank you for your time
% First code with simple recursion that flips end element one by one
function w=reversal_v2(v)
if length(v)==1
w= v;
else
w= [v(end),reversal_v2(v(1:end-1))];
end
% Second code with simple recursion that flips end element and first
% element together hence half the required time
b=1:1e4; %I/P vector
x=length(b); % To get length of vector
a=zeros(x);
for i=1:floor(length(b)/2) %Loop uses simple for loop and temp to substitute the values
tmp=b(i);
a(i)=b(x+1-i);
a(x+1-i)=tmp;
end

답변 (1개)

per isakson
per isakson 2021년 8월 12일
Five ways to flip a row vector. The last one, reversal_v3(), answers your question. Recursion is by two order of magnitude slower than the for-loop.
v = 1:1e4;
tic, v(end:-1:1); toc
Elapsed time is 0.000255 seconds.
tic, flip(v); toc
Elapsed time is 0.000254 seconds.
tic, reversal_v2(v); toc
Elapsed time is 0.274852 seconds.
tic, SecondCode(v); toc
Elapsed time is 0.001037 seconds.
tic, reversal_v3(v); toc
Elapsed time is 0.097940 seconds.
function w = reversal_v2(v)
% First code with simple recursion that flips end element one by one
if length(v)==1
w = v;
else
w = [v(end),reversal_v2(v(1:end-1))];
end
end
function a = SecondCode( b )
% Second code with simple recursion that flips end element and first
% element together hence half the required time
% b=1:1e4; % I/P vector
x = length(b); % To get length of vector
a = zeros(1,x); % Create row vector
% Loop uses simple for loop and temp to substitute the values
for ii = 1:floor(length(b)/2)
tmp=b(ii);
a(ii)=b(x+1-ii);
a(x+1-ii)=tmp;
end
end
function w = reversal_v3(v)
% ... replicate second code below in recursive way ...
if length(v) <= 2
w = flip( v );
else
w = [ v(end), v(end-1), reversal_v3(v(1:end-2)) ];
end
end
  댓글 수: 1
Rayyan Ramrajkar
Rayyan Ramrajkar 2021년 8월 14일
Thank you for your elaborate codes and I got the logic need to be implemented.
Regarding for loop vs recursion, I understand that simple loop approach is far more uperior than Recursion, but Recusrsion is must have requirement

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by