【问题标题】:Replacing letters with numbers in a MATLAB array用 MATLAB 数组中的数字替换字母
【发布时间】:2016-06-01 09:30:53
【问题描述】:

我正在尝试编写一个函数来标记测试结果。参与者给出的答案存储在一个 nx1 单元阵列中。但是,这些论文以字母形式存储。我正在寻找一种将(a-d)这些转换为数字(1-4)的方法,即。 a=1, b=2 因此可以使用逻辑运算比较答案。

到目前为止,我所拥有的是:
[num,txt,raw]=xlsread('FolkPhysicsMERGE.xlsx', 'X3:X142');
FolkPhysParAns=txt;

我似乎能够找到如何将数字转换为字母,但反之则不行。我觉得应该有一个相对简单的方法来做到这一点,有什么想法吗?

【问题讨论】:

  • 您可以使用 strrep 将 'a' 替换为 '1' (注意这是字符串格式),对所有 26 个字母执行此操作,然后使用 cell2mat 转换字符串 '1' - '26 ' 等到数字 1 -26。
  • nx1 数组的具体类型是什么?您可以编辑问题以包含示例吗?
  • 好的,我已经尝试添加信息,如果不是您需要的请告诉我。
  • 感谢@GameOfThrows 成功了!
  • 我在这里发现了这个[类似问题][1],在堆栈溢出中,我认为它可以帮助你:[1]:stackoverflow.com/questions/7606439/…

标签: matlab replace letters-and-numbers


【解决方案1】:

如果你有一个字母元胞数组:

>> data = {'a','b','c','A'};

你只需要:

  1. 使用lower 转换为小写,以平等对待这两种情况;
  2. cell2mat转换成字符数组;
  3. 减去(ASCII 码)'a' 并加上 1

代码:

>> result = cell2mat(lower(data))-'a'+1
result =
     1     2     3     1

更一般地,如果可能的答案不是连续的字母,甚至不是单个字母,请使用ismember

>> possibleValues = {'s', 'm', 'l', 'xl', 'xxl'};
>> data = {'s', 'm', 'xl', 'l', 'm', 'l', 'aaa'};
>> [~, result] = ismember(data, possibleValues)
result =
     1     2     4     3     2     3     0

【讨论】:

  • 不错的一个!比我的解决方案好得多!
【解决方案2】:

我想我不妨写一个答案... 您可以使用 strrep 将 'a' 替换为 '1' (注意它是字符串格式),并对所有 26 个字母执行此操作,然后使用 cell2mat 将字符串 '1' - '26' 等转换为数字 1 -26。

让我们说:

t = {'a','b','c'} //%Array of Strings
t = strrep(t,'a','1') //%replace all 'a' with '1' 
t = strrep(t,'b','2') //%replace all 'b' with '2'
t = strrep(t,'c','3') //%replace all 'c' with '3'
%// Or 1 line:
t = strrep(g,{'a','b','c'},{'1','2','3'})
>> t = 

'1'    '2'    '3'

output = cellfun(@str2num,t,'un',0)  //% keeps the cell structure

>> output = 

[1]    [2]    [3]

或者:

output = str2num(cell2mat(t'))   //% uses the matrix structure instead, NOTE the inversion ', it is crucial here.

>> output =
 1
 2
 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2020-01-31
    • 2016-10-08
    • 2017-08-16
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多