[英]Matlab: nested loops with if conditional
我正在嘗試通過迭代大小為(50000,21)的主矩陣中最后一列的行來構建子矩陣,並且如果內部的值大於1000,則整個對應的y(i,:)行將被添加到新的子矩陣,並從主矩陣中添加33個連續的行。
我在下面編寫了此代碼,但它僅返回33x21的大小,我想我正在遍歷j索引,但沒有遍歷i索引:
for i=1:50000
if y(i,21)>1000
for j=1:33
n(j,:)=y(j+i,:)
j=j+1
end
i=i+1
end
end
我究竟做錯了什么?
嘗試這個:
k=1;
for i=1:50000
if y(i,21)>1000
for j=0:33 %watch this out i am not sure how many rows you want to keep and if these involve the one with the last element greater than 1000 or not..%
n(k,:)=y(j+i,:);
j=j+1;
k=k+1;
end
i=i+1;
end
end
問題是每33條新記錄都將覆蓋前一行。我認為上述代碼可以解決問題。
這是不需要循環的矢量化版本:
%find elements that are greater than 1000
lo = find(y(:,21) > 1000);
%indeices of 33th row after the lo,
%since it may take a value that is greater than the size of matrix we limit this value by min
up = min(size(y,1), lo + 33);
% create indices based on ranges
%see http://stackoverflow.com/a/39434045/6579744
index=cumsum(accumarray(cumsum([1;up(:)-lo(:)+1]),[lo(:);0]-[0;up(:)]-1)+1);
index= index(1:end-1);
n = y(index, :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.