Executing loop on certain numbers

조회 수: 1 (최근 30일)
Raghavendra Reddy P
Raghavendra Reddy P 2015년 5월 11일
댓글: Raghavendra Reddy P 2015년 5월 11일
i have two vectors L=1:12; idx=[3 5 9]; I wanted to execute for loop for i=12:-1:1 now i want execute vector idx, starting from last elemet to first i.e 9,5,3 something like
if i==9
do stuff
end
if i==5
do stuff
end
.
.
if i==3
do stuff
end
end
i don't know how many elements in vector idx before hand.

채택된 답변

Stephen23
Stephen23 2015년 5월 11일
편집: Stephen23 2015년 5월 11일
You can execute over the vector backwards by using basic MATLAB indexing:
idx = [3,5,9];
for k = idx(end:-1:1)
... code here
end
  댓글 수: 3
Stephen23
Stephen23 2015년 5월 11일
편집: Stephen23 2015년 5월 11일
For a start you could use switch inside the loop:
for k = idx(end:-1:1)
switch k
case 9
... code
case 5
... code
case 3
... code
otherwise
error('This values is not known: %d',k)
end
end
But, depending on what those calculations are, there might be much easier and faster ways of achieving this. If you tell us exactly what the do stuff operations actually are, then we might be able to tidy this up too. Can the the vector idx change, or is it always the same?
Raghavendra Reddy P
Raghavendra Reddy P 2015년 5월 11일
Thank you sir, soon i will write what calculations and stuff to do. vector idx will change.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Subplots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by