How to vectorize nested for loops within a script

1 visualización (últimos 30 días)
Roba Kidse
Roba Kidse el 21 de Abr. de 2022
Respondida: Matt J el 21 de Abr. de 2022
%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

Respuestas (1)

Matt J
Matt J el 21 de Abr. de 2022
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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by