Search code examples
stringmatlabcell-array

How to preallocate and populate cell array in Matlab


dataset=importdata(filename);
[r,c]=size(dataset.data);
names2=dataset.textdata(2:r+1, 1);
names1=dataset.textdata(1, 2:c+1);
rc=r*c;
couples=cell(rc, 2);
k=1
for i=1:r
  for j=1:c
     couples{k}=[names2(i), names1(j)];
     k=k+1;
  end
end

The file contains a table, the first row and the first column contains two lists of strings representing names. I need to get all the couples of strings.

this is the workspace I'd like to have

names1   1xc cell
names2   1xr cell
couples  rcx2 cell

but when I visualize the couples I get

couples =
  1x2 cell  []
  1x2 cell  []
  1x2 cell  []
  ...

It should be

couples =
  nameA nameB
  nameC nameD
  nameE nameF
  ...

I know it is possible to get this result because importdata can do that and store the strings in textdata. When you visualize them you get

names1 =
  name1
  name1
  ... 

how can I get the desired result? How should I preallocate a cell array of rcx2 dimensions and assign each couple to the k-th row? I know I could get the results by concanation but it is too slow with thousands of rows.


Solution

  • Your implementation is almost correct. The reason why you have the cells in the second column is because you are assigning both pairs to the first column by using couples{k},if you want to assign the names from name2 to the first columns of the cell array use couples{k,1}, and for name1 to the second column of the cell array use couples{k,2}. Try the code is shown below.

    dataset=importdata(filename);
    [r,c]=size(dataset.data);
    names2=dataset.textdata(2:r+1, 1);
    names1=dataset.textdata(1, 2:c+1);
    rc=r*c;
    couples=cell(rc, 2);
    k=1
    for i=1:r
      for j=1:c
         couples{k,1}=[names2(i)];
         couples{k,2}=[names1(j)];
         k=k+1;
      end
    end