I have a vector, for example, (1,2,3,4) and I want to change the numbers into string

后端 未结 3 653
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 05:29

I have a vector, (1,2,3,4) and I want to label 1 with \'AA\', 2 with \'AB\', 3 with \'CD\', 4 with \'Hello\', wh

相关标签:
3条回答
  • 2021-01-23 05:49

    You probably want to use a cellstr array to store the output names, and use a mapping table to translate your inputs in to outputs.

    % List of labels that correspond to the indexes of the array
    labels = {'AA', 'AB', 'CD', 'Hello'};
    
    % Input vector
    v = [1 2 3 1 4 2];
    
    % Use multi-element indexing with () instead of {} to map them
    strs = labels(v);
    

    You'll get a cellstr array back of the same size as the input, containing the labels corresponding to the index value in each element. You can index in to it like strs{3} to get the individual labels out.

    0 讨论(0)
  • 2021-01-23 06:06

    MATLAB has a Map container type:

    keySet = 1:4;
    valSet = {'AA','AB','CD','Hello'};
    map = containers.Map(keySet,valSet);
    

    Get some requested values with the values method:

    >> vals = map.values(num2cell([3 2 1 4]))
    vals = 
        'CD'    'AB'    'AA'    'Hello'
    
    0 讨论(0)
  • 2021-01-23 06:11

    easy peasy, use a cell array, for example:

    v = {'AA','AB','CD','Hello'};
    

    then try,

    v{1}
    

    etc. (note the curly brackets...{})

    EDIT: this is parallel to :

    v{1}='AA';
    v{2}='AB'; ...
    ...
    
    0 讨论(0)
提交回复
热议问题