Matlab - Vectorize double for循环在单元格数组中查找唯一的单词标记

use*_*502 1 matlab for-loop vectorization

我有一个包含句子字符串的单元格数组x的单元格数组,我希望在x中找到所有唯一字标记的列表,然后使用它为数组结构创建字段名称y如果该字段名称尚不存在因为你 现在我使用double for循环迭代x中的每个句子字符串,然后迭代每个单独的单词来完成任务,但是当单元格数组包含太多字符串时它可能会非常慢.

for i=1:length(x)
    unique = unique(x{i});
    for j=1:length(unique)
            y.(unique{j}) = {};
    end
end
Run Code Online (Sandbox Code Playgroud)

样本输入:

x = {{'hello', 'world'}, {'foo', 'bar'}, {'eat', 'foo', 'ice', 'cream'}, {'hello', 'dad'}};
y = {};
Run Code Online (Sandbox Code Playgroud)

那么独特应该是这样的

unique = {'hello', 'world', 'foo', 'bar', 'eat', 'ice', 'cream', 'dad'}
Run Code Online (Sandbox Code Playgroud)

和结构数组y应该具有唯一的字段名称作为字段名称.所以应该有y.hello,y.world,y.foo,y.bar,y.eat,y.ice,y.cream和y.dad.只要根据需要输出长y,就不需要唯一的单词令牌列表.有没有办法通过矢量化或其他方式简化这些操作以使程序运行得更快?谢谢.

Sha*_*hai 5

你为什么这么unique说?如果你只是为每个单词构造一个空单元格,那么为什么你要关心你是否多次创建它?最后只剩下一个.

>> x = unique( [x{:}] );
>> y = cell2struct( cell(1, numel(x)), x, 2 )

y = 

      bar: []
    cream: []
      dad: []
      eat: []
      foo: []
    hello: []
      ice: []
    world: []
Run Code Online (Sandbox Code Playgroud)