我有一个带有字段的结构(sa1):FirstImpression,FashionSense,兼容性(7 * 1)大小
我想找到FirstImpression&的最大值的索引。时尚感并在同一索引上将兼容性值增加1。
我找到了最大值的索引,但是,我发现很难增加这些索引的兼容性值。
你能提出一个方法吗?这是代码:
firstImpression = zeros(1,size(sa1(),2));
fashionSense = zeros(1,size(sa1(),2));
for i=1:(size(sa1(),2))
firstImpression(i) = sa1(i).FirstImpression;
fashionSense(i) = sa1(i).FashionSense;
end
maxFirstImpressionScore = max(firstImpression);
maxFashionSenseScore = max(fashionSense);
maxFirstImpressionScoreIndexes = find(firstImpression == maxFirstImpressionScore);
maxFashionSenseScoreIndexes = find(fashionSense == maxFashionSenseScore);
for k = 1:size(maxFashionSenseScoreIndexes,2)
sa1(maxFashionSenseScoreIndexes(k)).Compatibility = sa1(maxFashionSenseScoreIndexes(k)).Compatibility +1;
end
有什么建议吗?
答案 0 :(得分:1)
在struct
条目数组上使用点表示法会产生this documentation,可用于形成数组。然后,您可以对这些数组进行操作,而不是每次循环遍历struct
。对于您的问题,您可以使用以下内容:
% Create an array of firstImpression values and find the maximum value
mx1 = max([sa1.firstImpression]);
% Create an array of fashionSense values and find the maximum value
mx2 = max([sa1.fashionSense]);
% Create a mask the size of sa1 that is TRUE where it was equal to the max of each
mask1 = [sa1.firstImpression] == mx1;
mask2 = [sa1.fashionSense] == mx2;
% Increase the Compatibility of struct that was either a max of firstImpression or
% fashionSense
compat = num2cell([sa1(mask1 | mask2).Compatibility] + 1);
% Replace those values with the new Compatibilty values
[sa1(mask1 | mask2).Compatibility] = compat{:};