Reputation: 3139
I am working in MATLAB and I did not find yet a way to split a table T in different tables {T1,T2,T3,...} dynamically. What I mean with dynamic is that it must be done based on some conditions of the table T that are not known a priori. For now, I do it in a non-dynamic way with the following code (I hard-code the number of tables I want to have).
%% Separate data of table T in tables T1,T2,T3
starting_index = 1;
T1 = T(1:counter_simulations(1),:);
starting_index = counter_simulations(1)+1;
T2 = T(starting_index:starting_index+counter_simulations(2)-1,:);
starting_index = starting_index + counter_simulations(2);
T3 = T(starting_index:starting_index+counter_simulations(3)-1,:);
Any ideas on how to do it dynamically? I would like to do something like that:
for (i=1:number_of_tables_to_create)
T{i} = ...
end
EDIT: the variable counter_simulations
is an array containing the number of rows I want to extract for each table. Example: counter_simulations(1)=200
will mean that the first table will be T1= T(1:200, :)
. If counter_simulations(2)=300
the first table will be T1= T(counter_simulations(1)+1:300, :)
and so on.
I hope I was clear.
Should I use cell arrays instead of tables maybe?
Thanks!
Upvotes: 0
Views: 141
Reputation: 1880
For the example you give, where counter_simulations
contains a list of the number of rows to take from T
in each of the output tables, MATLAB's mat2cell
function actually implements this behaviour directly:
T = mat2cell(T,counter_simulations);
While you haven't specified the contents of counter_simulations
, it's clear that if sum(counter_simulations) > height(T)
the example would fail. If sum(counter_simulations) < height(T)
(and so your desired output doesn't contain the last row(s) of T
) then you would need to add a final element to counter_simulations
and then discard the resulting output table:
counter_simulations(end+1) = height(T) - sum(counter_simulations);
T = mat2cell(T,counter_simulations);
T(end) = [];
Whether this solution applies to all examples of
some conditions of the table T that are not known a priori
you ask for in the question depends on the range of conditions you actually mean; for a broad enough interpretation there will not be a general solution but you might be able to narrow it down if mat2cell
performs too specific a job for your actual problem.
Upvotes: 1