MATLAB: Compacting a For Loop

if statement

Hi all
I would love some help with compacting a for loop, i'm using it to find the smallest error in a matrix is there a way of finding the smallest value of the matrix as well as the name of the variable associated with the smallest value other then printing out a masive for loop.
Thanks Ben.

Best Answer

norm_er = 1.301;
exp_er = 9.126;
log_er = 1.301;
ray_er = 2.606;
Errors = [norm_er,exp_er,log_er,ray_er];
% set a tolerance to define equal error
tol = 1e-3;
% find minimum error
min_error = min(Errors);
% find all methods with this error value
idxs = find((Errors-min_error) < tol);
error_str = ["Normal";"Exponential";"Log";"Rayleigh"];
% print based on how many errors are equal (extends to any number of distributions)
% none? that's not good
if length(idxs)==0
error('something went wrong')
% e.g., Rayleigh distribution is best
elseif length(idxs)=1
fprintf('%s Distribution is best\n',error_str(idxs))
elseif length(idxs)=length(Errors)
fprintf('All Distributions are equally good\n')
% e.g., Log and Rayleigh distributions are best
elseif length(idxs)=2
fprintf('%s and %s Distributions are best\n',error_str(idxs))
% e.g., Log, Exponential, and Rayleigh distributions are best
else
tmp = strjoin(error_str(idxs(1:end-1)),", ") + ", and " + error_str(idxs(end);
fprintf('%s Distributions are best',tmp)
end
Related Question