【问题标题】:Create a matrix of integers given a set of strings and a dictionary, in matlab在给定一组字符串和字典的情况下,在matlab中创建一个整数矩阵
【发布时间】:2026-02-16 18:35:01
【问题描述】:

我有一组字符串(作为 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

但是我得到的向量不正确。请帮忙!

【问题讨论】:

    标签: matlab dictionary matrix


    【解决方案1】:

    字符串应该存储为元胞数组。那么您可以使用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
    

    【讨论】: