Create a new array over each iteration

8 views (last 30 days)
Riccardo Tronconi on 14 Jun 2021
Edited: Rik on 16 Jun 2021
Hi guys! Starting from one table (A) I would divide it in n-table according to the max value of the A(:,4). At this point every each iteration I must create another table as it follows:
function [T_num2str(i)] = par(A)
n= max(A{:,4});
for i=1:n
search = find(A{:,4}==i);
eval(['T_' num2str(i) ' = table;']);
T_num2str(i) = position(search,:);
end
end
I have two problem:
1- How to define output values if I do not know how many they would be?
2- How to solve this indexing problem ?
T_num2str(i) = position(search,:);
Stephen23 on 15 Jun 2021
"I need it parametric so Its functioning is still valid if max(indices) is either lower or greater. "
Sure, but you did not answer Rik's question.
So far there is no obvious reason why you cannot use simpler indexing, rather than your complex and inefficient approach.

Rik on 14 Jun 2021
The code below gives you what you want. The only difference is that you need to write my_data{1} instead of my_data1.
data = 12×6 cell array
{'Location'} {[1.6149e+18]} {'lab'} {[1]} {[2.6936]} {[3.5776]} {'Location'} {[1.6149e+18]} {'lab'} {[2]} {[2.5642]} {[3.5736]} {'Location'} {[1.6149e+18]} {'lab'} {[3]} {[2.6610]} {[3.5411]} {'Location'} {[1.6149e+18]} {'lab'} {[2]} {[2.6049]} {[3.5502]} {'Location'} {[1.6149e+18]} {'lab'} {[3]} {[2.6080]} {[3.5852]} {'Location'} {[1.6149e+18]} {'lab'} {[3]} {[2.6523]} {[3.5085]} {'Location'} {[1.6149e+18]} {'lab'} {[3]} {[2.6343]} {[3.5355]} {'Location'} {[1.6149e+18]} {'lab'} {[2]} {[2.6998]} {[3.5359]} {'Location'} {[1.6149e+18]} {'lab'} {[2]} {[2.6149]} {[3.5874]} {'Location'} {[1.6149e+18]} {'lab'} {[1]} {[2.6527]} {[3.4991]} {'Location'} {[1.6149e+18]} {'lab'} {[1]} {[2.6670]} {[3.5399]} {'Location'} {[1.6149e+18]} {'lab'} {[1]} {[2.6206]} {[3.5023]}
indices=cell2mat(data(:,4));
my_data=cell(max(indices),1)
for n=1:max(indices)
my_data{n}=data(indices==n,:);
end
my_data
my_data = 3×1 cell array
{4×6 cell} {4×6 cell} {4×6 cell}
my_data{1}
ans = 4×6 cell array
{'Location'} {[1.6149e+18]} {'lab'} {[1]} {[2.6936]} {[3.5776]} {'Location'} {[1.6149e+18]} {'lab'} {[1]} {[2.6527]} {[3.4991]} {'Location'} {[1.6149e+18]} {'lab'} {[1]} {[2.6670]} {[3.5399]} {'Location'} {[1.6149e+18]} {'lab'} {[1]} {[2.6206]} {[3.5023]}
Rik on 16 Jun 2021
You made the mistake of using length and assuming it would return the number of rows. The length function does not guarantee that. Use size(my_data{1},1) instead if you want the number of rows. You might also want to learn about the numel function if you want to loop over all elements of an array.