Info

この質問は閉じられています。 編集または回答するには再度開いてください。

improve performance of this code

1 回表示 (過去 30 日間)
Salvatore Mazzarino
Salvatore Mazzarino 2012 年 11 月 10 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
suppose to have a matrix called A
3 0 3 3
0 0 4 0
and have this function
while(1)
if all(A(:,i) == 0)
i = i + 1;
else
i = i + 1
break;
end
end
How can I improve the performance of this code?
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 11 月 10 日
What do you want to find?
Salvatore Mazzarino
Salvatore Mazzarino 2012 年 11 月 10 日
I want to find the index that rappresents the column where there are at least one element

回答 (3 件)

Jan
Jan 2012 年 11 月 10 日
編集済み: Jan 2012 年 11 月 10 日
I cannot imagine that you can feel the speedup for such a tiny problem.
k = 1; % Avoid using "i" as variable
while(1)
if any(A(:, k)) % This saves the creation of the temp logical vector
k = k + 1;
break;
else
k = k + 1
end
end
Note that you function will crash, when A contains zeros only. More secure:
index = NaN;
for k = 1:size(A, 2)
if any(A:, k)
index = k;
break;
end
end
Now index is a NaN, if no column matches the condition.
Shorter:
k = find(any(A, 1), 1);
For large A this must be slower, if a matching column appears early.
  1 件のコメント
Salvatore Mazzarino
Salvatore Mazzarino 2012 年 11 月 10 日
i variable is important in my code. it's incremented during the execution of my code. it cannot be fixed

Matt J
Matt J 2012 年 11 月 10 日
編集済み: Matt J 2012 年 11 月 10 日
i = find(any(A,1) ,1)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 11 月 10 日
編集済み: Azzi Abdelmalek 2012 年 11 月 10 日
out= min(find(any(A)))
%or
ii= 1;
while(1)
if any(A(:,ii))
break;
else
ii= ii+1
end
end

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by