How to identify and erase the cells with the error "Error using fit>iFit (line 348). NaN computed by model function, fitting cannot continue" in an array?

Dear community,
I have an array (720*1 cell) where in each cell, I have a set of variables x and y. I am estimating the best fit curve for each set. However, my loop stops and gives me the error: "Error using fit>iFit (line 348). NaN computed by model function, fitting cannot continue. Try using or tightening upper and lower bounds on coefficients."
How to identify all the cells with this error and remove them from the array? This is the code that I use:
ft1= fittype( 'power2');
for k = 1 : length(Array_january)
fit_curve{k}= fit(x{k},y{k},ft1);
end
Thank you in advance!

6 Commenti

If you want only to get rid of the error, you can use try/catch:
ft1= fittype( 'power2');
fit_curve = cell(length(Array_january), 1); % never forget preallocation!
for k = 1:length(Array_january)
try
fit_curve{k} = fit(x{k}, y{k}, ft1);
catch
fprintf('error encountered index:%d\n', k)
end
end
@Ive J Thank you very much for the reply. What do you mean by "get rd of the error", does it mean that try and catch eliminates the "k's" that cause the error?
By the way, thanks for remind me the preallocation :)
@Ive J I also occasionally get the following message:
"Warning: NaN, Inf, or complex value detected in startpoint; choosing random starting point instead."
However, it does not identify this as an error, as the estimate is done. How can I get try and catch to identify this and likewise identify the "k´s"?
What I meant was my approach does not fix the error, and only skips those indices (k's) for which fit cannot do the fitting; and that's what exactly catch does. Simply put, you try a function (or a piece of code) and if some error happens MATLAB goes to catch statement and runs the codes under that section. To see fit function failed for which k indices, you can check those empty cells in fit_curve:
failedIdx = find(cellfun(@isempty, fit_curve));
@Ive J Thank you very much! I don't see where I can accept your answer :(

Accedi per commentare.

 Risposta accettata

ft1= fittype( 'power2');
fit_curve = cell(length(Array_january), 1); % never forget preallocation!
for k = 1:length(Array_january)
try
fit_curve{k} = fit(x{k}, y{k}, ft1);
catch
fprintf('error encountered index:%d\n', k)
end
end
failedIdx = find(cellfun(@isempty, fit_curve));

Più risposte (0)

Richiesto:

il 15 Dic 2021

Commentato:

il 16 Dic 2021

Community Treasure Hunt

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

Start Hunting!

Translated by