Assigning nested tables inside a parfor-loop

조회 수: 6 (최근 30일)
Benedikt Prusas
Benedikt Prusas 2021년 6월 28일
답변: Seth Furman 2021년 6월 28일
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

채택된 답변

Seth Furman
Seth Furman 2021년 6월 28일
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.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2021년 6월 28일
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.

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by