Reverse an array by for loop

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

 채택된 답변

Wayne King
Wayne King 2012년 10월 10일

0 개 추천

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

Mohammed
Mohammed 2012년 10월 10일
IT does not work.. when i input this in the matlab it gives me nothing
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.
Matt Fig
Matt Fig 2012년 10월 10일
편집: Matt Fig 2012년 10월 10일
Wayne, Mohammed needs to read the Getting Started section of the documentation. As far as I can tell, he thinks it doesn't work because of the semi-colons. See the comments on my answer for more insight.

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

추가 답변 (2개)

Doug Hull
Doug Hull 2012년 10월 10일

0 개 추천

a = fliplr(a)

댓글 수: 2

Mohammed
Mohammed 2012년 10월 10일
it must be for loop
Doug Hull
Doug Hull 2012년 10월 10일
why?

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

Matt Fig
Matt Fig 2012년 10월 10일

0 개 추천

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

Mohammed
Mohammed 2012년 10월 10일
i put this in the matlab but i do not know what's wrong it does not give me an output
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.....

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2012년 10월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by