In MATLAB, I want to convert a vector of text elements into numbers in order to plot them.

后端 未结 1 1768
别跟我提以往
别跟我提以往 2020-12-11 11:11

In MATLAB, I want to convert a vector of text elements into numbers in order to plot them.

For example, say I have the following data

team = [blue g         


        
相关标签:
1条回答
  • 2020-12-11 12:05

    I'm assuming the text elements are in a cell array, like so:

    team = {'blue', 'green', 'blue', 'yellow', 'green', 'blue'};
    

    It isn't possible to make a normal vector / array with multiple strings, as this would basically create a single string that concatenates all of these strings together. You'd have to split them up into a cell array... now onto your question.

    You can use the third output parameter of unique. This output basically assigns each unique element in an array or cell array a unique ID number. In this case, if you did:

    [~,~,id] = unique(team)
    

    ... we would get:

    id =
    
     1
     2
     1
     3
     2
     1
    

    ... which is exactly what you want!


    As a bonus for you, we can easily plot this, changing the x axis to each of those labels. In other words:

    score = [20 45 74 10 11 42].'; %// Transpose as id is transposed '
    plot(id, score, 'b.', 'MarkerSize', 16);  % // Plot the points
                                              % // Marker size is 16
    set(gca, 'XTick', 1:3); %// Only set three ticks to 
                            %// be visible as there are 3 IDs
    xlim([0 4]); %// Make the x-axis bigger
    set(gca, 'XTickLabel', ...
       {'blue', 'green', 'yellow'}); %// Change the numeric labels to text
    grid; %// Put a grid on
    

    ... and this is the figure I get:

    enter image description here

    0 讨论(0)
提交回复
热议问题