matlab - 在 MATLAB 中,我想将文本元素向量转换为数字以便绘制它们。

标签 matlab

在 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

...这是我得到的数字:

enter image description here

关于matlab - 在 MATLAB 中,我想将文本元素向量转换为数字以便绘制它们。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25175223/

相关文章:

python - MATLAB ActiveX 与 Python Win32COM

Matlab VideoReader 花费了意想不到的时间

python - 使用 Anaconda 安装 "MATLAB Engine for Python"时出现问题

matlab - 如何使用 CUDA 在 GPU 上运行 MATLAB 代码?

matlab - 如何从 MATLAB 输出中抑制 "ans"行?

c++ - 编译C dll部署MATLAB代码时出现错误C2371

使用 Latex 解释器的 Matlab 图例文本溢出

matlab - 在子图中设置两个 y Axis 颜色

java - 从 Java 调用 matlab 回调/函数句柄

Matlab 未绘制精确的傅里叶信号