How to get one table instead of multiple tables.

this is my code
for i=1:100
num = randi([1 75], 1, 5);
ex_num = randi([1 15], 1 , 1);
x=sort(num);
s = horzcat(x, ex_num);
table(i,s(1),s(2),s(3),s(4),s(5),s(6),'VariableNames', {'iter' 'first' 'second' 'third' 'fourth' 'fifth' 'extra'}, 'RowNames' ,{'iteration'})
end
for i=1:100 num = randi([1 75], 1, 5); ex_num = randi([1 15], 1 , 1); x=sort(num); s = horzcat(x, ex_num); table(i,s(1),s(2),s(3),s(4),s(5),s(6),'VariableNames', {'iter' 'first' 'second' 'third' 'fourth' 'fifth' 'extra'}, 'RowNames' ,{'iteration'}) end
Once I run the code I get what I want, however, I get 100 separate tables instead just getting one continuous table.

1 Comment

Although beginners love using table, it is much tidier and more robust to use cell2table or struct2table, rather than converting from list of workspace variables using table.
Using these functions significantly reduces workspace clutter and is much more robust!

Sign in to comment.

 Accepted Answer

you have two methods, to either add to the table instead of creating a new table or create the table at the end and build a matrix storing all the data.
for i=1:5
num = randi([1 75], 1, 5);
ex_num = randi([1 15], 1 , 1);
x=sort(num);
iteration(i,1)=i;
s = horzcat(x, ex_num);
S(i,:) = horzcat(x, ex_num);
T(i,:)=table(i,s(1),s(2),s(3),s(4),s(5),s(6),'VariableNames', {'iter' 'first' 'second' 'third' 'fourth' 'fifth' 'extra'}, 'RowNames' ,{'iteration'});
end
table(iteration,S(:,1),S(:,2),S(:,3),S(:,4),S(:,5),S(:,6),'VariableNames', {'iteration' 'first' 'second' 'third' 'fourth' 'fifth' 'extra'})
so in the sample code i added two methods. 1 is to create the table variable T which appends to the existing table instead of generating a new table.
The other is the last line and the S(i,:) which generates the table at the end. you cannot have duplicate row names so i removed your iteration label for each row. additionally you've already labeled it in column 1.

2 Comments

Thanks a lot this makes a lot of sense.
Although beginners love using table, it is much tidier and more robust to use cell2table or struct2table, rather than converting from list of workspace variables using table.
Using these functions significantly reduces workspace clutter and is much more robust!

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!