在Matlab数组中用字符串替换数字

4

我有一个MATLAB中的数字数组,例如:

a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];

我希望用字符串替换数字。

例如,1 =“苹果”; 2 =“你好”; 3 =“再见”;

例如,我可以使用其他数字进行替换。

a(a==1) = 999
a(a==2) = 998

但是我需要通过替换字符串来完成同样的事情。对我来说并不容易,有人能帮我吗?谢谢,Matilde

3个回答

5

如果您的数字始终以1开头,且每个数字都需要替换,则只需进行索引:

>> mp={'apples','hello','goodby'}

mp = 

    'apples'    'hello'    'goodby'

>> a = [1 1 1; 2 2 1; 3 3 2]

a =

     1     1     1
     2     2     1
     3     3     2

>> mp(a)

ans = 

    'apples'    'apples'    'apples'
    'hello'     'hello'     'apples'
    'goodby'    'goodby'    'hello' 

3
这可能是一种处理包含字符串和数字混合数据的单元数组输出的方法 -
%// Numeric array and cell array of input strings 
a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];
names = {'apples','hello','goodbye'}

%// Create a cell array to store the mixed data of numeric and string data 
a_cell = num2cell(a)

%// Get the mask where the numbers 1,2,3 are which are to be replaced by
%// corresponding strings
mask = ismember(a,[1 2 3])

%// Insert the strings into the masked region of a_cell
a_cell(mask) = names(a(mask))

代码运行 -

a =
     1     1     1
     2     2     1
     3     3     2
     4     5     1
names = 
    'apples'    'hello'    'goodbye'
a_cell = 
    'apples'     'apples'     'apples'
    'hello'      'hello'      'apples'
    'goodbye'    'goodbye'    'hello' 
    [      4]    [      5]    'apples'

最后一行可以替换为 a_cell(mask)=names(a(mask)) 以简化代码。 - Daniel
1
@Daniel 刚刚已经做了 :) - Divakar

0

我不知道你是否真的想要替换值或创建一个包含相同大小字符串的新数组。正如其他人指出的那样,你需要一个单元数组来存储这些字符串。

a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];
aStrings = cell(3,4)
aStrings(a==1) = {'apples'}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接