MATLAB: How to fix when I give value to cell in a blank table, the rest of the un-valued cells in the same row will be set as double format automatically

array2tablecell arraysMATLABnon-cell content to cell arrays

Hi, I have used array2table to create a two column blank table (the table has only header when it created). And the specific contents for each cell at each row are filled in by loop. The problem is, after I give the first value to the first cell (it is a string), then the first row created and the second cell in the same row is defined as non-cell (i.e. default is 0, which is a double). So when I tried to give the second cell a string, the program stops me doing so as it states "Cell contents assignment to a non-cell array object". But I did the same thing before with so many .m file, it never happen to me. Funny thing is, i checked with an old workable file and it cannot be execute as well with the same error. Could anyone kindly help me with this please? Many thanks. The code is simplified as follow:
network=readtable('New Microsoft Excel Worksheet.xlsx');
network.Properties.VariableNames{1}='Region';
network.Properties.VariableNames{2}='Depot';
network.Properties.VariableNames{3}='Customer';
route=array2table(zeros(0,2));
route.Properties.VariableNames{1}='From';
route.Properties.VariableNames{2}='To';
k=1;
for i=1:1:size(unique(network.Depot),1)
for j=1:1:size(unique(network.Depot),1)
if strcmp(network.Depot{i},network.Depot{j})==0
route.From{k,1}=network.Depot{i};
route.To{k,1}=network.Depot{j};
k=k+1;
end
end
end

Best Answer

You are creating a table with 0 rows, but the table has two variables, both of which are doubles. Empty, but doubles.
>> route = array2table(zeros(0,2))
route =
0×2 empty table
>> route.Var1
ans =
0×1 empty double column vector
You are not going to be able to assign text values into those variables, you will need to create the empty table with text variables, either cell arrays, or strings. Something like
route = table(strings(0,1),strings(0,1));
It might also be worth looking into using categorical variables for those node names, rather than raw text.
Also, your best bet is to preallocate to the correct number of rows. The way you've framed this problem, it appears that you don't know that, but there are better ways to frame it. You have what I guess is an NxN cell array called Depot, containing depot names.
i = ~strcmp(Depot,Depot')
gives you a logical indicating which elements are not symmetric, which is what I think you are doing. Sum those and divide by two, and you have the number of rows in your table.
And at that point, you don't need any loops. From is just Depot(i) and To is the same on Depot'.