1

我有一个结构 (sa1) 字段:FirstImpression、FashionSense、兼容性 (7*1) 大小

我想找到 FirstImpression & Fashion Sense 最大值的索引,并在同一索引上将 Compatibility 的值增加 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

有什么建议么 ?

4

1 回答 1

1

struct在条目数组上使用点表示法会产生一个逗号分隔的列表,可用于形成数组。然后,您可以对这些数组进行操作,而不是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{:};
于 2017-03-27T18:11:27.543 回答