Nested for loop fit with function

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by