Assigning nested tables inside a parfor-loop
13 views (last 30 days)
Show older comments
Benedikt Prusas
on 28 Jun 2021
Answered: Seth Furman
on 28 Jun 2021
I use parfor for paralelisation, and create an table as LOG which contains a nested table.
Runing the following code will result in the following Error:
Subscripted assignment dimension mismatch for table variable 'Var2'.
VarTypes={'double','table'};
LOG=table('Size',[1 2],'VariableTypes',VarTypes);
parfor i=1:1
nested_table=table(2,3);
table_row=table(i,nested_table);
LOG(i,:)=table_row;
end
My suboptimal solution is to fill the table before the parfor loop:
But is there a cleaner way?
%create first entry
i=1;
nested_table=table(1,1);
table_row=table(1,nested_table);
LOG=table_row;
%concentrate table with duplicates of this entry
for i=2:10
LOG=[LOG;table_row];
end
%run in parallel
parfor i=2:10
nested_table=table(5,5);
table_row=table(i,nested_table);
LOG(i,:)=table_row;
end
0 Comments
Accepted Answer
Seth Furman
on 28 Jun 2021
Adding to Walter's answer:
The table constructor does not allow specifying the widths of individual variables when preallocating with the 'Size' and 'VariableTypes' parameters. One way we can get around this is to preallocate each variable individually and then call the table constructor.
For example
% Preallocate LOG
Var1 = zeros([3 3]);
Var2 = table('Size',[3 2],'VariableTypes',["double","double"]);
LOG = table(Var1,Var2);
% Populate LOG
for i = 1:10
nested_table = table(i*2,i*5);
LOG(i,:) = table(i,nested_table);
end
It's worth noting that, in this toy example, there's no benefit to using a parfor loop. See the following page in the documentation for advice on when to use a parfor loop.
0 Comments
More Answers (1)
Walter Roberson
on 28 Jun 2021
The problem is that
LOG=table('Size',[1 2],'VariableTypes',VarTypes);
is creating LOG.Var2 as a 1 x 0 table, but you are trying to assign in a 1 x 2 table.
If you assign a 1 x 2 table to LOG.Var2 before-hand, then the assignments will function properly.
0 Comments
See Also
Categories
Find more on Parallel for-Loops (parfor) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!