我有一组字符串(作为Nx1矩阵)和一个包含字符串中所有单词的字典(Mx1)。 例如:
strings= ['i went to the mall'; 'i am hungry']
dictionary = ['i','went','to','the', 'mall','am','hungry']
我想创建一个矩阵(大小为MxN),如果相应的单词出现在相应的推文中,则单元格包含1。我怎么能在matlab中做到这一点?
我试过这样做:
for i=1:len_of_dict
for j=1:len_of_str
temp=strfind(string1(j),dict(i));
x=find(cellfun(@isempty,temp));
xx = isempty(x);
if(xx~=0)
vec(i,j)=1;
end
end
end
但我得到的矢量不正确。请帮忙!
答案 0 :(得分:0)
字符串应存储为单元格数组。然后,您可以使用strsplit
打破推文,然后使用ismember
检查推文中每个单词的存在。
strings= {'i went to the mall'; 'i am hungry'};
dictionary = {'i','went','to','the', 'mall','am','hungry'};
splitted_strings = cellfun(@(x) strsplit(x,' '), strings, 'UniformOutput', false);
presence = cellfun(@(s) ismember(dictionary, s), splitted_strings, 'UniformOutput', false);
您可以使用vertcat
将结果转换为矩阵:
out = vertcat(presence {:})
结果:
1 1 1 1 1 0 0
1 0 0 0 0 1 1