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개)

Matt J
Matt J 2022년 4월 21일

0 개 추천

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에 대해 자세히 알아보기

제품

릴리스

R2018a

질문:

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