Make matlab save results to the same table but different rows

Hi I got a while loop that calculates the size of a vector for several columns of data. I was wondering if there is a method to save all the outputs to one table in different rows. Many thanks in advance.

 Accepted Answer

I would store the values within the while loop and then convert the array to a table using array2table.
rng('default')
x = [];
z = rand();
while z > .01
x(end+1) = z;
z = rand();
end
T = array2table(x(:),'VariableName',{'myVar'})
T = 122×1 table
myVar _______ 0.81472 0.90579 0.12699 0.91338 0.63236 0.09754 0.2785 0.54688 0.95751 0.96489 0.15761 0.97059 0.95717 0.48538 0.80028 0.14189

6 Comments

How would this change of I had 4 variables?
rng('default')
x = [];
z = rand(1,4);
while any(z > .05)
x(end+1,:) = z;
z = rand(1,4);
end
T = array2table(x,'VariableName',{'v1','v2','v3','v4'})
T = 105919×4 table
v1 v2 v3 v4 _______ ________ ________ ________ 0.81472 0.90579 0.12699 0.91338 0.63236 0.09754 0.2785 0.54688 0.95751 0.96489 0.15761 0.97059 0.95717 0.48538 0.80028 0.14189 0.42176 0.91574 0.79221 0.95949 0.65574 0.035712 0.84913 0.93399 0.67874 0.75774 0.74313 0.39223 0.65548 0.17119 0.70605 0.031833 0.27692 0.046171 0.097132 0.82346 0.69483 0.3171 0.95022 0.034446 0.43874 0.38156 0.76552 0.7952 0.18687 0.48976 0.44559 0.64631 0.70936 0.75469 0.27603 0.6797 0.6551 0.16261 0.119 0.49836 0.95974 0.34039 0.58527 0.22381 0.75127 0.2551 0.50596 0.69908
BTW if you know the number of iterations, it's much better to use a for-loop and preallocate your loop variable.
For example,
rng('default')
n = 10;
x = nan(n,4);
for i = 1:n
x(i,:) = rand(1,4);
end
T = array2table(x,'VariableName',{'v1','v2','v3','v4'})
T = 10×4 table
v1 v2 v3 v4 _______ ________ ________ ________ 0.81472 0.90579 0.12699 0.91338 0.63236 0.09754 0.2785 0.54688 0.95751 0.96489 0.15761 0.97059 0.95717 0.48538 0.80028 0.14189 0.42176 0.91574 0.79221 0.95949 0.65574 0.035712 0.84913 0.93399 0.67874 0.75774 0.74313 0.39223 0.65548 0.17119 0.70605 0.031833 0.27692 0.046171 0.097132 0.82346 0.69483 0.3171 0.95022 0.034446
If I post my code would you be able to take a look. I have attempted your method, but I think I am doing something wrong. Thanks for your contribution
Sure, include only the relevant sections, describe the size of your data, and share any error messages you're getting.
I figured it out after changing the names of my variables. Thanks a lot for the examples.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 4 May 2021

Commented:

on 14 May 2021

Community Treasure Hunt

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

Start Hunting!