Search code examples
matlabmatlab-struct

Update Values of a field in structure | Matlab


I have a structure (sa1) with fields : FirstImpression, FashionSense, Compatibility (7*1) size

I want to find the indexes of maximum value of FirstImpression & Fashion Sense and increment the value of Compatibility by 1 on the same index.

I have found the indexes of maximum value, However, I am finding it difficult to increment the compatibility value on those indexes.

Can you suggest a way ? Here is the code :

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

Any suggestions ?


Solution

  • Using dot notation on an array of struct entries yields a comma separated list which can be used to form arrays. You can then operate on these arrays rather than looping through the struct every time. For your problem, you could use something like:

    % 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{:};