Nested for loop fit with function

1 回表示 (過去 30 日間)
William
William 2014 年 4 月 22 日
コメント済み: William 2014 年 4 月 22 日
I understand for loops are not ideal for Matlab, but not sure how to avoid using them. In this case I have a matrix 'TE_ROI' that contains values at each position which need to be run through a function 'multi_exp_fit'. It fits 2 exponential curves to the data and then puts the coefficients inside another preallocated matrix. Here is the code. Please advise.
T2_gof = zeros(s_x,s_y,s_z,numel(X));
T2_range1= zeros(s_x,s_y,s_z,numel(X));
T2_range2= zeros(s_x,s_y,s_z,numel(X));
for x = 1:s_x
for y = 1:s_y
for z = 1:s_z
for v = 1:s_v
[fitresult,gof] = multi_exp_fit(TE,ROI(:,x,y,z,v));
out = coeffvalues(fitresult);
T2_gof(x,y,z,v) = gof.rsquare;
T2_range1(x,y,z,v) = (-1/out(2));
T2_range2(x,y,z,v) = (-1/out(4));
end
end
end
end

採用された回答

Jan
Jan 2014 年 4 月 22 日
It is interesting, that you understand, that loops are not ideal for Matlab. I've heard of this rumor in the times of Matlab 6.1 also. But since the year 2002 and release 6.5 the introduction of the JIT acceleration improved the speed of loops substantially.
So my advice is to be happy with the loop, as long as it does not consume more than 25% of the total computing time. And even if it is the bottleneck, it is not worth to spend 1 hour in the vectorization, when you save 0.1 seconds of runtime.
  2 件のコメント
William
William 2014 年 4 月 22 日
Thanks for your rapid response Jan. The looping issue is probably because I am new to it. It currently takes over half an hour to run, the results are fine but would be nice to make it faster. Or is this expected?
William
William 2014 年 4 月 22 日
I've isolated the bottleneck to this, if it helps:
for x=1:s_x
for y=1:s_y
for z=1:s_z
for v=1:s_v
[fitresult, gof] = fit( xData, squeeze(yData(:,x,y,z,v)), ft, opts );
out = coeffvalues(fitresult);
T2_gof(x,y,z,v) = gof.rsquare;
T2_range1(x,y,z,v) = (-1/out(2));
T2_range2(x,y,z,v) = (-1/out(4));
end
end
end
end

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

その他の回答 (0 件)

カテゴリ

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