Search code examples
arraysmatlabvectorizationcell-array

MATLAB: Use values in double array to determine values in a cell array of strings


I have a 597x4 double array that constitutes student marks in a subject. Each value in that array is between 0 and 100.

I want to create an 597x4 cell array of strings, where each cell contains a string connected to the equivalent location in the double array.

Everyone who scored 80 or more gets an 'A'. Therefore, if (1,1) of the double array contains 84 then (1,1) of the cell array should be 'A'. Let's say the breakdown is > 80 = 'A', < 80 but > 50 = 'B', and otherwise 'C'.

I realise this could easily be done with a loop, but is there a more elegant way? This is in MATLAB, but ultimately I want to paste the values into an Excel file.


Solution

  • Here's one with bsxfun and some reshaping -

    factions = [0,30,50,80] %// Edit this if you want more factions
    remarks = {'Doomed','Fail','Good','Very good'}; %// Editable too
    
    rank = sum(bsxfun(@ge,arr,permute(factions,[1 3 2])),3);
    out = reshape(cellstr(char(max(rank(:))-rank(:)+'A')),size(arr))
    out_remarks = remarks(rank)
    

    Sample input, output -

    arr =
         3    81    73    38    88
        56    90    58    94    94
        31    60     3    83    67
        94    89    45    85    21
        99    95    65    38    66
        29    55    53    60     8
    factions =
         0    30    50    80
    out = 
        'D'    'A'    'B'    'C'    'A'
        'B'    'A'    'B'    'A'    'A'
        'C'    'B'    'D'    'A'    'B'
        'A'    'A'    'C'    'A'    'D'
        'A'    'A'    'B'    'C'    'B'
        'D'    'B'    'B'    'B'    'D'
    out_remarks = 
        'Doomed'       'Very good'    'Good'      'Fail'         'Very good'
        'Good'         'Very good'    'Good'      'Very good'    'Very good'
        'Fail'         'Good'         'Doomed'    'Very good'    'Good'     
        'Very good'    'Very good'    'Fail'      'Very good'    'Doomed'   
        'Very good'    'Very good'    'Good'      'Fail'         'Good'     
        'Doomed'       'Good'         'Good'      'Good'         'Doomed'