cell2mat conversion in MATLAB (For ismember)
I need to convert a column in 2 matrices to the same datatype
so that I can run ismember
. One column is in matrix开发者_如何学运维 []
format and the other is in string format i.e. we need to match [2000]
with '2000'
. Please see:
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';} ;
Shall appreciate a vectorized code, if possible.
If you know that all of the second column of mat2
is going to be strings, you could convert them to numbers like so:
mat2(:,2) = cellfun(@str2num, mat2(:,2), 'UniformOutput', false)
Iterating through would also work, particularly if you're not sure they're all strings:
for i=1:size(mat2,1)
if ischar(mat2{i,2})
mat2{i,2} = str2num(mat2{i,2});
end
end
From what I understand, you want to merge the rows from the two sets based on the second column. Here is my implementation:
%# 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)];
The result:
>> merged
merged =
'ex' [ 10] 'abc'
'aa' [2001] 'ghi'
'rt' [4001] 'def'
精彩评论