How to vectorize nested for loops within a script
조회 수: 1 (최근 30일)
이전 댓글 표시
%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
댓글 수: 0
답변 (1개)
Matt J
2022년 4월 21일
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!