我有一个50000 * 2的单元格,其中包含数字内容。现在我想替换第二列,其数字范围从1到10,对应的字符串如'airplane'表示1,'automobile'表示2,依此类推。什么是最有效的方法? 我首先尝试将第二列内容拆分为新的单元格class1并将其转换为字符串并尝试通过应用以下代码进行替换:
classes1(strcmp('1',classes1))={'airplane'};
classes1(strcmp('2',classes1))={'automobile'};
classes1(strcmp('3',classes1))={'bird'};
classes1(strcmp('4',classes1))={'cat'};
classes1(strcmp('5',classes1))={'deer'};
classes1(strcmp('6',classes1))={'dog'};
classes1(strcmp('7',classes1))={'frog'};
classes1(strcmp('8',classes1))={'horse'};
classes1(strcmp('9',classes1))={'ship'};
classes1(strcmp('10',classes1))={'truck'};
但那并不成功。它只用'卡车'代替'10'。
更新:此代码实际上有效。但在我的情况下,必须使用字符串'1'而不是'1'(缺少空格)。
答案 0 :(得分:1)
使用此功能扩展到您的大案例 -
%%// Create look up and numeral data cell arrays for demo
LOOKUP_CELL_ARRAY = {'airplane','automobile','chopper'};
IN_CELL_ARRAY = num2cell(round(1+2.*rand(10,2)))
%%// Replace the second column of data cell array with corresponding
%%// strings in the look up array
IN_CELL_ARRAY(:,2)= LOOKUP_CELL_ARRAY(cell2mat(IN_CELL_ARRAY(:,2)))
输出 -
IN_CELL_ARRAY =
[2] [2]
[2] [2]
[2] [1]
[2] [2]
[3] [1]
[2] [3]
[1] [1]
[3] [3]
[2] [2]
[2] [3]
IN_CELL_ARRAY =
[2] 'automobile'
[2] 'automobile'
[2] 'airplane'
[2] 'automobile'
[3] 'airplane'
[2] 'chopper'
[1] 'airplane'
[3] 'chopper'
[2] 'automobile'
[2] 'chopper'
答案 1 :(得分:1)
您可以使用cellfun
执行以下操作:
% replacement strings
R = {'airplane','automobile','bird','cat','deer', ...
'dog','frog','horse','ship','truck'};
% example data
nums = randi(10,100,1);
data(:,1) = num2cell(nums)
data(:,2) = cellstr(num2str(nums))
data =
[ 3] ' 3'
[ 1] ' 1'
[ 1] ' 1'
[ 8] ' 8'
[ 8] ' 8'
[ 8] ' 8'
[ 7] ' 7'
[ 9] ' 9'
[ 1] ' 1'
...
str2double(x)
不关心其'01'
或'1'
:
% replicate number strings with strings
data(:,2) = cellfun(@(x) R( str2double(x) ), data(:,2) )
data =
[ 3] 'bird'
[ 1] 'airplane'
[ 1] 'airplane'
[ 8] 'horse'
[ 8] 'horse'
[ 8] 'horse'
[ 7] 'frog'
[ 9] 'ship'
[ 1] 'airplane'
...
答案 2 :(得分:1)
您只需使用索引编制即可:
data = {'aa' 1
'bb' 3
'cc' 2
'dd' 6
'ee' 1
'ff' 5}; %// example data: two-col cell array, 2nd col is numbers
str = {'airplane','automobile','bird','cat','deer', ...
'dog','frog','horse','ship','truck'}; %// replacement strings
data(:,2) = str(vertcat(data{:,2})); %// do the replacing