Checking whether string exist in a cell and read its ID
2 次查看(过去 30 天)
显示 更早的评论
I have a cell array called "proteins_selected" and each row is a code for a protein, looks like this:
Then I would like to translate each protein code into its ID, so i have another cell array "GoAnnotationsWithId" which is like a dictionary(the second row is ID):
So i would like to chech whether proteins from proteins_selected exist in GoAnnotationsWithId file, and get appropriate ID of this protein. I would be extremely grateful for any help.
0 个评论
采纳的回答
Stephen23
2021-5-15
The simple, efficient MATLAB approach would be to use ISMEMBER:
A = {'banana',12;'orange',23;'apple',35;'peach',74;'pear',51;'cherry',62}
B = {'apple','bldf','orange'}
[X,Y] = ismember(B,A(:,1));
V = nan(size(X));
V(X) = [A{Y(X),2}]
更多回答(1 个)
DGM
2021-5-14
Something like this may work
LUT = {'banana',12;
'orange',23;
'apple',35;
'peach',74;
'pear',51;
'cherry',62};
% random assortment of fruit names
mydata = LUT(randi(6,10,1),1)
% if you want the output to be a numeric vector
f = @(x) LUT{strcmp(x,LUT(:,1)),2};
output = cellfun(f,mydata)
gives
mydata =
10×1 cell array
{'cherry'}
{'orange'}
{'apple' }
{'peach' }
{'peach' }
{'peach' }
{'banana'}
{'pear' }
{'cherry'}
{'banana'}
output =
62
23
35
74
74
74
12
51
62
12
Alternatively:
% if you want the output to be a cell vector
f = @(x) LUT(strcmp(x,LUT(:,1)),2);
output = cellfun(f,mydata)
2 个评论
DGM
2021-5-14
编辑:DGM
2021-5-14
Oh I see what's going on. The problem is that there are elements in your list that aren't in the dictionary. This complicates things. I ended up having to write a function to handle undefined cases:
LUT = {'banana',12;
'orange',23;
'apple',35;
'peach',74;
'pear',51;
'cherry',62};
% random assortment of fruit names
mydata = [LUT(randi(6,10,1),1); {'bldf'}]
% if you want the output to be a numeric vector
f = @(x) actualfunction(x,LUT);
output = cellfun(f,mydata)
function out = actualfunction(x,LUT)
m = strcmp(x,LUT(:,1));
if any(m)
out = LUT{m,2};
else
out = NaN; % or whatever default value you want
end
end
There may be more elegant ways of doing this.
If it turns out that these problem entries are to be discarded anyway, you could also do this instead.
% if you only want to keep valid entries
f = @(x) any(strcmp(x,LUT(:,1)));
mydata = mydata(cellfun(f,mydata)); % get rid of bad entries
f = @(x) LUT{strcmp(x,LUT(:,1)),2};
output = cellfun(f,mydata) % do lookup like first example
I doubt it's as fast or faster, but it's more compact.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Genomics and Next Generation Sequencing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!