我需要将2个矩阵中的列转换为same datatype
,以便我可以运行ismember
。一列采用矩阵[]
格式,另一列采用字符串格式,即我们需要将[2000]
与'2000'
匹配。请参阅:
mat1 = {'aa' [2001] ; 'ex' [10] ; 'ex' [1001] ; 'rt' [4001] ;} ;
mat2 = {'abc' '10' ; 'def' '4001' ; 'ghi' '2001' ; } ;
ismember(cell2mat(mat1(:,2)), cell2mat(mat2(:,2))) % Gives ERROR
%cell2mat(mat1(:,2) works just fine
%cell2mat(mat2(:,2)) is the PROBLEM.
%Final answer
ans = {...
'aa' [2001] 'ghi'; 'ex' [10] 'abc'; 'ex' [1001] 'abc'; 'rt' [4001] 'def';} ;
如果可能,应该欣赏矢量化代码。
答案 0 :(得分:1)
如果你知道mat2
的所有第二列都是字符串,你可以将它们转换成这样的数字:
mat2(:,2) = cellfun(@str2num, mat2(:,2), 'UniformOutput', false)
迭代通过也会奏效,特别是如果你不确定它们都是字符串:
for i=1:size(mat2,1)
if ischar(mat2{i,2})
mat2{i,2} = str2num(mat2{i,2});
end
end
答案 1 :(得分:0)
据我所知,您希望根据第二列合并两个集合中的行。这是我的实施:
%# data
mat1 = {'aa' [2001] ; 'ex' [10] ; 'ex' [1001] ; 'rt' [4001] ;} ;
mat2 = {'abc' '10' ; 'def' '4001' ; 'ghi' '2001' ; } ;
%# sorted row keys
[key1 ord1] = sort( cell2mat(mat1(:,2)) );
[key2 ord2] = sort( str2double(mat2(:,2)) );
%# match rows based on key
[idx1 loc1] = ismember(key1,key2);
[idx2 loc2] = ismember(key2,key1);
%# merge
merged = [mat1(ord1(loc2(idx2)),:) mat2(ord2(loc1(idx1)),1)];
结果:
>> merged
merged =
'ex' [ 10] 'abc'
'aa' [2001] 'ghi'
'rt' [4001] 'def'