how to find minimum value of output corresponds to which input values in a loop/nested loop ? Error i am getting is Index exceeds the number of array elements.
1 view (last 30 days)
Show older comments
i want to find for what value of c and what value of hh , the genError is minimum. The error i am getting is Index exceeds the number of array elements. Index must not exceed 1.
load fisheriris
X = meas;
Y = species;
TTT=0;
for c=[0.05 0.1]
for hh=[0.1 1]
TTT=TTT+1;
t = templateSVM('Standardize',true,'KernelFunction','gaussian','kernelscale',c,'boxconstraint',hh);
Mdl = fitcecoc(X,Y,'Learners',t,'FitPosterior',true,...
'ClassNames',{'setosa','versicolor','virginica'},...
'Verbose',2);
CVMdl = crossval(Mdl);
genError(TTT) = kfoldLoss(CVMdl);
end
end
[mingenaratederror min_index] = min(genError);
c_kscale = c(min_index); % get the corresponding value from the c array
hh_boxcon = hh(min_index); % get the corresponding value from the hh array
0 Comments
Accepted Answer
Voss
on 18 Mar 2022
Note that after a for loop completes, the value of the loop iterator is the value it had during the last iteration of the loop:
TTT=0;
for c=[0.05 0.1]
for hh=[0.1 1]
TTT=TTT+1;
end
end
c % last value of c is 0.1
hh % last value of hh is 1
(An exception to this is when the loop iterates over an empty array, in which case the iterator is empty after the loop, but that's not the case here.)
The point is that c and hh are scalars, so indexing them with min_index can generate the error you saw. If you want to find the values of c and hh that correspond to the minimum value of genError, it may be convenient to create c and hh as vectors with the appropriate sequences of values:
[hh,c] = ndgrid([0.1 1],[0.05 0.1]);
c = c(:)
hh = hh(:)
Now c and hh have all the values they need, in the same order as they have in your nested loops, so you can replace your nested loops with a single loop, and the single loop can use TTT to index into c and hh:
load fisheriris
X = meas;
Y = species;
for TTT = 1:numel(c)
t = templateSVM( ...
'Standardize',true, ...
'KernelFunction','gaussian', ...
'kernelscale',c(TTT), ... % c is a vector now: need to index with TTT
'boxconstraint',hh(TTT)); % same for hh
Mdl = fitcecoc(X,Y, ...
'Learners',t, ...
'FitPosterior',true,...
'ClassNames',{'setosa','versicolor','virginica'},...
'Verbose',2);
CVMdl = crossval(Mdl);
genError(TTT) = kfoldLoss(CVMdl);
end
Now finding the values of c and hh corresponding to the minimum value of genError will work correctly:
[mingenaratederror min_index] = min(genError);
c_kscale = c(min_index); % get the corresponding value from the c array
hh_boxcon = hh(min_index); % get the corresponding value from the hh array
disp(min_index);
disp(c_kscale);
disp(hh_boxcon);
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!