FOR loop with IF condition alternative

1 回表示 (過去 30 日間)
Agent Cooper
Agent Cooper 2014 年 8 月 5 日
回答済み: Agent Cooper 2014 年 8 月 5 日
I have the following code
I = [1:1:10; 10:10:100]'
a = size(I)
limit1 = 1
limit2 = 3
limit3 = 7
limit4 = 10
for j = 1:a(2)
X = I(:,j)
for k = 1:a(1)
if (k>limit1 && k<limit2) || (k>limit3 && k<limit4)
Y = 0
else Y = X(k)
end
B(k) = Y
end
C{j} = B'
end
that replaces the 2nd, the 8th and the 9th elements on each column with 0. For the example above, the [1 2 3 4 5 6 7 8 9 10; 10 20 30 40 50 60 70 80 90 100] matrix is replaced with the [1 0 3 4 5 6 7 0 0 10; 10 0 30 40 50 60 70 0 0 100] matrix.
Could anyone give me a hint on how to do this without using the FOR loop and the IF condition (because they are very slow when processing big amounts of data)?

採用された回答

Hikaru
Hikaru 2014 年 8 月 5 日
Try this
I = [1:1:10; 10:10:100]';
I(2,:) = 0;
I(8,:) = 0;
I(9,:) = 0;
  2 件のコメント
Agent Cooper
Agent Cooper 2014 年 8 月 5 日
Dear Hikaru,
Of course this is a solution to my simple example. But, please, consider the case in which you do not have only 3 indexes, but 10 or more and placed in different intervals (e.g. 84 to 98 and 758 to 767). I need something that works automatically, like the FOR loop.
Hikaru
Hikaru 2014 年 8 月 5 日
Sorry, I failed to notice it.
One way I can think of is something like this.
I = [1:1:10; 10:10:100]';
a = size(I);
limit = [2,3,9]; % specify the rows you want to be 0 here
for i=1:a(2)
I(limit(i),:) = 0;
end
I'm assuming you want the whole row be 0, but let me know if that's not the case.

サインインしてコメントする。

その他の回答 (2 件)

Amir
Amir 2014 年 8 月 5 日
編集済み: Amir 2014 年 8 月 5 日
Please try this code. You will only need to specify your limits (L matrix)
I = [1:1:10; 10:10:100]';
L = [1 3 7 10]; % limit Matrix
NewL=vec2mat(L,2);
R=[]; %Removed rows
for i=1:size(NewL,1)
R=[R NewL(i,1)+1:NewL(i,2)-1];
end
I(R,:)=0; % or I(R,:)=[] if you want to remove those rows

Agent Cooper
Agent Cooper 2014 年 8 月 5 日
Thank you very much, Hikaru and Amir. Both answers were of great use.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by