更新结构中字段的值 |软件

Update Values of a field in structure | Matlab

我有一个包含以下字段的结构 (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

有什么建议吗?

struct 个条目的数组上使用点符号会产生一个 comma separated list,可用于形成数组。然后您可以对这些数组进行操作,而不是每次都循环遍历 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{:};