How to vectorize nested for loops within a script

%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

回答(1 个)

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.

类别

在 帮助中心 和 File Exchange 中查找有关 Structures 的更多信息

提问:

2022-4-21

回答:

2022-4-21

Community Treasure Hunt

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

Start Hunting!

Translated by