function [fval, fit_seed, n_f, fix_params] = ...
run_fits(f, fix_s, fix_params, fit_s, fit_seed, skip,...
fit_domain, prec)
% RUN_FITS using parfor to sweep parameters for droplet FRAP
% data/simulations.
% PARAMETERS:
% skip ... enumerates the movies/sims. Any nans will be skipped.
% Use for refitting.
% Run fits for all sets of fixed parameters
n_f = repmat(skip, size(fix_params, 2), 1);
n_f = n_f(:);
fix_params = repmat(fix_params, 1, length(f));
prec = repmat(prec, 1, length(f));
opt = optimset('MaxFunEvals', 300, 'PlotFcns',@optimplotfval, ...
'TolFun', 1e-08, 'TolX', 1e-08);
fval = zeros(1, size(fit_seed, 2));
% Check whether f is data or simulation, if data, make sure D_i is given
test_for_class = f{1};
wh = whos('test_for_class');
if strcmp(wh.class, 'FRAP_mov'); is_exp=1; else is_exp = 0; end
if is_exp && ~strcmp(fix_s{1}, 'D_i')
disp('When experimental data given, first fixed variable must be D_i.');
return;
end
% Run all fits in parallel
% parpool(71);
parfor i = 1:size(fix_params, 2)
fix_p = fix_params(:, i);
% in case of experimental data: calculate D_i.
if is_exp && ~isnan(n_f(i))
D_i = abs(f{n_f(i)}.conv_factor_D*f{n_f(i)}.x_seed);
fix_p(1) = D_i;
end
to_min_an = @(x) to_min(x, fit_s, fix_p, fix_s, f{n_f(i)},...
fit_domain, prec(i));
if isnan(n_f(i))
fval(i) = nan;
fit_seed(:, i) = nan;
disp(['Not fitting parameter set ', num2str(i)]);
elseif ~isempty(fit_s)
disp(['Calculating set ', num2str(i)]);
[x_seed, fval1] = fminsearch(to_min_an, fit_seed(:, i), opt);
fit_seed(:, i) = x_seed;
fval(i) = fval1;
else
fval1 = to_min([], fit_s, fix_p, fix_s, f{n_f(i)},...
fit_domain, prec(i));
fit_seed(:, i) = nan;
fval(i) = fval1;
end
end
end