Nested for loop fit with function

2 views (last 30 days)
William
William on 22 Apr 2014
Commented: William on 22 Apr 2014
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

Accepted Answer

Jan
Jan on 22 Apr 2014
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 Comments
William
William on 22 Apr 2014
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 on 22 Apr 2014
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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!