Reverse an array by for loop
29 ビュー (過去 30 日間)
古いコメントを表示
Hi i got this array : a=[1 2 3 4 5] and i want to reverse it by for loop so it will be a=[5 4 3 2 1]
Thanks
0 件のコメント
採用された回答
Wayne King
2012 年 10 月 10 日
Why a for loop?
a = [1 2 3 4 5] ;
b = fliplr(a);
If you must with a for loop
for ii = 1:length(a)
b(ii) = a(length(a)-ii+1);
end
3 件のコメント
Wayne King
2012 年 10 月 10 日
a = [1 2 3 4 5] ;
for ii = 1:length(a)
b(ii) = a(length(a)-ii+1);
end
It absolutely works. Just copy and paste the entire code snippet above into the command window.
その他の回答 (2 件)
Matt Fig
2012 年 10 月 10 日
An in-place FOR loop would look like:
a = 1:10;
L = length(a);
for ii = 1:L/2
T = a(L-ii+1);
a(L-ii+1) = a(ii);
a(ii) = T;
end
2 件のコメント
Matt Fig
2012 年 10 月 10 日
You need to read the "Getting Started" section of the documentation. Copy-paste the code I gave into the command window and it will reverse the elements of a. Nothing is wrong, you just didn't look at a after the code ran!! To look at the result, type:
a
at the command window.....
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!