How to vectorize nested for loops within a script
Show older comments
%The script:
PopList = {popCA_1,popCA_2,popCA_3,popCA_4}; % PopList is a 1 by 4 cell with 30 by 1 struct
b = [b1,b2,b3,b4]; % b is a 1 by 4 struct with 1 by 1 struct
start = false;
for d = 1:4
lbest = b(d).Situational.accuracy;
for f = 1:30
data = PopList{d}(f);
PopList{d}(f) =newFunc(data,lbest,X,T);
end
PopList{d} = SortPop(PopList{d});
newBeliefs = PopList{d}(1:newBeliefNo);
worst = PopList{d}(nPop);
b(d) = UpdateBeliefSystem(b(d), newBeliefs, worst, start);
end
%The newFunc:
function [popdata] = newFunc(popdata,lbest,X,T)
featSize = size(X,2);
cProb = 0.2; % probability of change
nChange = round(cProb*featSize); % number of features changed
if (popdata.accuracy < lbest)
%apply change operator (flip the values at the gene location)%
f = randperm(featSize, nChange);
for i=1:size(f,2)
popdata.Position(f(i)) = mod(( popdata.Position(f(i)))+1,2);
end
f1 = find(popdata.Position ==1);
popdata.nfeat = size(f1,2);
X1 = X(:,(f1));
%
[popdata.accuracy, popdata.AUCval,popdata.mse,...
popdata.OPTROCPT,popdata.precision,popdata.F1,popdata.recall ] = knn(X1,T);
end
end
Answers (1)
Matt J
on 21 Apr 2022
0 votes
You cannot vectorize loops over cells and structs. In most cases, cells and structs are appropriate only for small data sizes (which appears to be your case as well), so there is usually no need to vectorize them.
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!