在 MATLAB 中,我想将文本元素向量转换为数字以便绘制它们。
例如,假设我有以下数据
team = [blue green blue yellow green blue];
score = [20 45 74 10 11 42];
我想像这样使用分散
scatter(team, score)
因此,沿着 x 轴我有三个(即团队中唯一元素的数量)标签(蓝色、绿色和黄色),y 轴显示每个分数。
所以我需要将向量team
转换为数字,例如team = [1 2 1 3 2 1];
还是什么?
最佳答案
我假设文本元素位于元胞数组中,如下所示:
team = {'blue', 'green', 'blue', 'yellow', 'green', 'blue'};
不可能用多个字符串创建一个普通的向量/数组,因为这基本上会创建一个将所有这些字符串连接在一起的单个字符串。您必须将它们分成一个元胞数组...现在讨论您的问题。
可以使用unique
的第三个输出参数。此输出基本上为数组或元胞数组中的每个唯一元素分配一个唯一的 ID 号。在这种情况下,如果您这样做:
[~,~,id] = unique(team)
...我们会得到:
id =
1
2
1
3
2
1
...这正是您想要的!
作为对您的奖励,我们可以轻松地绘制此图,将 x
轴更改为每个标签。换句话说:
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
...这是我得到的数字:
关于matlab - 在 MATLAB 中,我想将文本元素向量转换为数字以便绘制它们。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25175223/