Reverse character array using recursion
古いコメントを表示
I'm having trouble creating a function that would reverse a character array using recursion. For example, I want my function to return 'py' when inputting "yp". My overall code doesn't seem right though.
function array2 = charReversal(array1)
if array1==0
return;
else
array2=chsrReversal(reverse(array1,array1-1));
disp(array2)
end
採用された回答
その他の回答 (5 件)
Anuj Kumar
2020 年 10 月 9 日
instead of using v=[v(end) reversal(1:end-1)] which won't satisfactorily on large arrays,i would recommend this piece of code
function v=reversal(v)
if(length(v)>1)
d=length(v);
x=0;
if mod(d,2)==0
x1=d/2;
x2=x1+1;
m=v(1:x1);
n=v(x2:end);
v=[reversal(n),reversal(m)];
else
x1=fix(d/2);
x2=x1+2;
m=v(1:x1);
mid=(x1+1:x1+1);
n=v(x2:end);
v=[reversal(n),v(mid),reversal(m)];
end
end
end
Saurabh Wani
2020 年 8 月 17 日
i have try this code and it gives reversal of array elements using recursive method
function w=reversal(v)
s=length(v)
if s==1
w=v
else
w=[v(end) reversal(V(1:s-1))]
end
2 件のコメント
Hazem Ahmed
2020 年 8 月 19 日
編集済み: Walter Roberson
2020 年 8 月 20 日
could you explain what are you doing in this line?
w=[v(end) reversal(V(1:s-1))]
Piyush Gupta
2020 年 9 月 10 日
編集済み: Piyush Gupta
2020 年 9 月 10 日
its an array, you can declare without comma too.
KSSV
2017 年 10 月 17 日
You can either use fliplr or give indices in reverse.
str = 'py' ;
fliplr(str)
str(end:-1:1)
4 件のコメント
Todd Wilson
2017 年 10 月 17 日
編集済み: Todd Wilson
2017 年 10 月 17 日
KSSV
2017 年 10 月 17 日
Oh dear friend.... str is the string which should be input...in your case it is array1. Your function should be simply:
function array2 = charReversal(array1)
array2=array1(end:-1:1) ;
Save it, it will be saved on the name charReversal.m. To call/ use it:
array2 = charReversal('py')
array1 = 'matlab' ;
array2 = charReversal(array1)
Todd Wilson
2017 年 10 月 17 日
KSSV
2017 年 10 月 17 日
Ohh..why recursion needed? That case you may add it. But don't use str.
ambuj aman
2020 年 9 月 15 日
function out = reversal(in)
if length(in) <= 1
out = in;
else
out = [ reversal(in(2:end)) in(1) ];
end
end
Selman Baysal
2022 年 1 月 8 日
I solve this problem by removing first and last elements in the vector until one or zero element remains.
function w = reversal(v)
if length(v) <= 1
w = v;
else
v1 = v(end); v(end) = [];
v2 = v(1); v(1) = [];
w = [v1 reversal(v) v2];
end
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!