2011-07-29 7 views
0

2つの行列の列をsame datatypeに変換して、ismemberを実行する必要があります。 1つの列は行列[]形式であり、もう1つは文字列形式です。つまり、[2000]'2000'を一致させる必要があります。参照してください:MATLABのcell2mat変換(ismemberの場合)

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';} ; 

可能であれば、ベクトル化コードを理解してください。

答えて

1

あなたがmat2の2番目の列の全てが文字列であることを行っていることがわかっている場合、あなたはそのような数値に変換できます。

を反復
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 
0

私が理解しているように、2番目の列に基づいて2つのセットから行をマージしたいとします。ここに私の実装です:

%# 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' 
関連する問題