Q:

Matlab - Vectorize double for loop to find unique word tokens in a cell array

I have a cell array of cell array x that contains sentence strings, and I want to find a list of all unique word tokens in x and then use it to create field names for an array structure y if that field name doesn't already exist for y. Right now I'm using a double for loop to iterate over each sentence string in x, then iterate over each individual unique word to accomplish the task, but it can be quite slow when the cell array contains too many strings.
for i=1:length(x)
    unique = unique(x{i});
    for j=1:length(unique)
            y.(unique{j}) = {};
    end
end

Sample input:
x = {{'hello', 'world'}, {'foo', 'bar'}, {'eat', 'foo', 'ice', 'cream'}, {'hello', 'dad'}};
y = {};

then unique should be such that
unique = {'hello', 'world', 'foo', 'bar', 'eat', 'ice', 'cream', 'dad'}

and structure array y should have all word tokens in unique as field names. So there should be a y.hello, y.world, y.foo, y.bar, y.eat, y.ice, y.cream and y.dad. The unique list of word tokens is not necessary as long as long y is outputted as desired. Is any way to streamline these operations through vectorizing or otherwise to make the program run faster? Thanks.

A:

Why do you do unique for the words? If you simply construct an empty cell per word, than why do you care if you create it several times? In the end only one will remain.
>> x = unique( [x{:}] );
>> y = cell2struct( cell(1, numel(x)), x, 2 )

y = 

      bar: []
    cream: []
      dad: []
      eat: []
      foo: []
    hello: []
      ice: []
    world: []

