Looping with indices that are not equally spaced

조회 수: 13 (최근 30일)
John F
John F 2011년 6월 23일
댓글: Walter Roberson 2019년 12월 22일
I'm trying to run a loop on a group of indices I obtained using "find". The indices will not always be consecutive. So, running a for loop like:
for i = indices
won't work. I'm trying to avoid doing something like:
for i = 1:length(VECTOR)
Any ideas?
  댓글 수: 2
Oleg Komarov
Oleg Komarov 2011년 6월 23일
not clear why it won't work. Depends how you structure the operations inside the loop. Post more code.
Daniel Shub
Daniel Shub 2011년 6월 23일
What do you mean it doesn't work? What would you expect to get with:
indices = [1,2,3,5,7,13,11];
for i = indices, i, end

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

채택된 답변

Laura Proctor
Laura Proctor 2011년 6월 23일
Actually, it will work.
for idx = [ 1 -2 10 12.5 0 ]
disp(idx)
end
Isn't MATLAB cool?

추가 답변 (2개)

John F
John F 2011년 6월 23일
So, it works with a row vector of indices, but not a column?
I tried that bit of code but transposed idx, and the loop didn't work. Strange?
  댓글 수: 2
Laura Proctor
Laura Proctor 2011년 6월 23일
편집: Walter Roberson 2019년 12월 22일
You are correct - check out Loren's Blog, it explains this behavior much better than I can:
Daniel Shub
Daniel Shub 2011년 6월 23일
편집: Walter Roberson 2019년 12월 22일
Yeah, but check out what it does do with a column. You should have a read of:

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


Frederick Abangba Akendola
Frederick Abangba Akendola 2019년 12월 22일
Please, how do I write a “For” loop with irregular interval? For example; 2,4,8,16,32
  댓글 수: 1
Walter Roberson
Walter Roberson 2019년 12월 22일
for K = 2.^(1:5)
result = whatever involving K
end
However, most of the time you want to create one output per input. The general way to do that is
K_vals = 2.^(1:5);
numK = numel(K_vals);
results = zeros(size(K_vals));
for K_idx = 1 : numK
K = K_vals(K_idx);
results(K_id) = whatever involving K
end
plot(K_vals, results)

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by