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

37 次查看(过去 30 天)
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 个评论

请先登录,再进行评论。

更多回答(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