FOR loops optimisation for runtime

Is there a way to optimise this code? It takes a long time to run.
It basically comprises of 3 FOR loops running like this:
A=linspace(0,1,100);
B=linspace(0,1,100);
C=linspace(0,1,100);
zmatrix=zeros(length(A),length(B))
for i=1:length(A)
for j=1:length(B)
for k=1:length(C)
Z=A(i)+B(j)-C(k)
if Z>0
Z=zmatrix(i,j)
end
end
end
end

3 件のコメント

Matt J
Matt J 2013 年 6 月 27 日
Z=A(i)+B(j)-C(k)
Shouldn't this be
Z(i,j,k) = A(i)+B(j)-C(k)
James
James 2013 年 6 月 27 日
I just have it as Z in my code. I missed out a bit at the start where I create a zeros matrix of size (length A,length B) and then the Z values get put into that matrix in their relevant places. So had no need for it being Z(i,j,k).
Matt J
Matt J 2013 年 6 月 27 日
編集済み: Matt J 2013 年 6 月 27 日
Rewrite your code showing how each matrix element (i,j) is calculated. If the matrix is only 100x100 it is not clear why you are looping over 100^3 combinations of i,j,k.

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

回答 (1 件)

Matt J
Matt J 2013 年 6 月 27 日
編集済み: Matt J 2013 年 6 月 27 日

0 投票

This might be what you want, depending on your response to my Comment above.
A=A(:);
B=B(:).';
C=reshape(C,1,1,[]);
Z=bsxfun(@plus,A(:),B(:).');
Z=bsxfun(@minus,Z,C);

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2013 年 6 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by