【问题标题】:Replacing string values in cell array with numbers用数字替换元胞数组中的字符串值
【发布时间】:2023-04-04 16:43:01
【问题描述】:

我有一个包含一些描述的元胞数组,即my_des

 my_des = [{'FRD'} {'1'}; {'UNFRD'} {'2'}; {'OTH'} {'3'};];

我还有一个大约 5000x1 的单元阵列。此数组中的元素是'FRD''UNFRD''OTH'

我要做的是将这些文本值替换为my_des 中的相应数值。

目前我唯一的想法(我认为这不是很好)是循环通过my_des 并进行字符串替换。


示例

所以说我当前的向量是这样的:

FRD
FRD
OTH
UNFRD
OTH
FRD

那么我想要的输出是这样的:

1
1
3
2
3
1

数字来自my_des 数组

【问题讨论】:

  • 这些值'1''2''3' 不存在于您的原始数组中吗?如果这些值来自my_des,为什么不直接选择第二列?

标签: matlab cell-array


【解决方案1】:

您要使用字符 '1''2''3' 还是只使用数字 123 ?区别是1行答案和2行答案的区别!

根据您的示例,让我们使用以下数据:

arr = {'FRD'; 'FRD'; 'OTH'; 'UNFRD'; 'OTH'; 'FRD'};

获取arr 中每个元素在my_des 内的行索引,并使用它来获取对应的第二列值...

% If you just want the *number* then this is all you need
[~, idx] = ismember(arr, my_des);
% idx is the row within column 1 of my_des where the value in arr is found
% >> idx = [1; 1; 3; 2; 3; 1]

% If you want to get the values my_des then use idx as a row index
out = mydes(idx, 2);
% out is the corresponding values from the 2nd column of my_des, whatever they may be.
% >> out = {'1'; '1'; '3'; '2'; '3'; '1'};

除此之外:您为什么要通过连接 my_des 的 1 元素元胞数组来声明一个元胞数组?相反,您可以这样做:

my_des = {'FRD',   '1'; 
          'UNFRD', '2'; 
          'OTH',   '3'};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2015-04-23
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    相关资源
    最近更新 更多