フィルターのクリア

Inefficient code - simple counter

1 回表示 (過去 30 日間)
Joppy
Joppy 2017 年 12 月 15 日
コメント済み: KL 2017 年 12 月 15 日
I have the following inefficient bit of code.
for i = 1:n %arb n
if something
A(i,1) = A(i,1) + 1;
elseif somethingelse
A(i,2) = A(i,2) + 1;
end
end
There are actually 5 if/else clauses inside a function which is called inside the loop, but I've reduced it to the above for simplicity. For large n, this is very slow. Is there a faster way to do this? It's supposed to be a simple counter that retains information about the counts.
Thanks
edit: I have filled A with zeros before the loop also.
  2 件のコメント
KL
KL 2017 年 12 月 15 日
What are your conditions? Give an example.
Joppy
Joppy 2017 年 12 月 15 日
編集済み: Joppy 2017 年 12 月 15 日
I'm checking if one number is smaller than another. While they do contribute to the overall time, it isn't nearly as problematic as the counter (I've timed with and without).

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

採用された回答

KL
KL 2017 年 12 月 15 日
I suppose your condition is something like checking the range of the specific element. Depending on what range they are in you want to perform something on that specific element.
A = rand(50,1);
ind1 = A<0.25; %first if
ind2 = A>=0.25&A<0.5; %elseif
ind3 = A>=0.5&A<0.75;
ind4 = ~ind1&~ind2&~ind3; %else
B = (A+1).*ind1+(A+2).*ind2+(A+3).*ind3+(A+4).*ind4;
  2 件のコメント
Joppy
Joppy 2017 年 12 月 15 日
Oh. No the conditions aren't related to A, but I can adapt this approach anyway.. Silly me. Thanks!
KL
KL 2017 年 12 月 15 日

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

その他の回答 (1 件)

Birdman
Birdman 2017 年 12 月 15 日
編集済み: Birdman 2017 年 12 月 15 日
One approach:
Consider a B vector with dummy data.
B=randi([1 10],20,1);A=zeros(numel(B),2);
ind1=find(B<5);%condition1
ind2=find(B>=5);%condition2
A(ind1,1)=1;A(ind2,2)=1;

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by