Help with for loop - How do I use indices to denote intervals?

조회 수: 37 (최근 30일)
Kristen
Kristen 2013년 10월 12일
댓글: Kristen 2013년 10월 12일
I have a vector A, for example (1:1:600)'.
I have a matrix B with indices denoting which rows of A that I want to perform a calculation on. These indices are in intervals - B(:,1) is the start and B(:,2) is the end of each interval - for example B(:,1)=[5,15,25,35,45] and B(:,2)=[10,20,30,40,50] (corresponding to intervals 5-10,15-20,25-30,35-40,45-50).
I want to use the intervals specified in B to change something about A. This needs to happen for various reasons in my data, but for simplicity let's say I want to change values in the rows corresponding to those intervals to zero. I have been trying to use a for loop but I am missing something.
I have: for i=B(:,1); for j=B(:,2); A(i:j,:)=0; end; end;
Now, I would hope that this would change the values of rows 5-10,15-10,25-30,35-40,45-50 to 0, but the command is only executed for the first interval (rows 5-10), not the rest.
I am pretty new to Matlab and so I am sure I am missing some subtle and easy thing here. I have tried searching through all of the help topics and other people's questions but I can't find anyone else trying to use the indices as intervals.

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 10월 12일
편집: Azzi Abdelmalek 2013년 10월 12일
Edit
n=size(B,1);
for k=1:n;
ii=B(k,1)
jj=B(k,2)
A(ii:jj,:)=0;
end
  댓글 수: 3
Kristen
Kristen 2013년 10월 12일
편집: Kristen 2013년 10월 12일
Thanks! This works great - you are awesome!

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

추가 답변 (1개)

sixwwwwww
sixwwwwww 2013년 10월 12일
Dear Kristen, you can do like this:
A = [1:600]';
B = [1:24]';
count = 0;
for i = 1:2:length(B)
multicative = 50;
C(i, :) = A(5 + multicative * count:10:45 + multicative * count);
C(i + 1, :) = A(10 + multicative * count:10:50 + multicative * count);
count = count + 1;
end
disp(C)
Now you can take values form Matrix C for corresponding indices in vector A. I hope it is what you need if I understood correctly. Good luck!

카테고리

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