Clear Filters
Clear Filters

How can I arrange (collect) values for a couple of variables into a table outside "for loop" ?

4 views (last 30 days)
I have used "dataset" command to arrange the values of "B,R2,m,c" in a table like format; that is in a "for loop" which repeats 20 times. However, matlab shows the results independently per each trial as the following (I have pasted here only 4 trials just to understand it and not all the 20 trials);
ans =
B R2 m c
1 0.98463 0.35271 13.224
ans =
B R2 m c
2 0.96652 0.26335 12.687
ans =
B R2 m c
3 0.95112 0.21396 13.082
ans =
B R2 m c
4 0.93795 0.18173 13.783
My Question is: How can I tell Matlab to give me all the above values under one heading (I mean to look like a table format) as in the following (which I did it by my hand):
B R2 m c
1 0.98463 0.35271 13.224
2 0.96652 0.26335 12.687
3 0.95112 0.21396 13.082
4 0.93795 0.18173 13.783

Answers (1)

Jacob Halbrooks
Jacob Halbrooks on 18 Mar 2014
This looks like a good use case for the TABLE function in MATLAB. You can create a table with your data variables and get a nice display of your data:
>> B = [1;2;3;4];
>> R2 = [0.98463; 0.96652; 0.95112; 0.93795];
>> m = [0.35271; 0.26335; 0.21396; 0.18173];
>> c = [13.224; 12.687; 13.082; 13.783];
>> t = table(B,R2,m,c)
t =
B R2 m c
_ _______ _______ ______
1 0.98463 0.35271 13.224
2 0.96652 0.26335 12.687
3 0.95112 0.21396 13.082
4 0.93795 0.18173 13.783
See the Tables doc for related functions and examples of adding and removing data from a table.
  2 Comments
Hameed Salih
Hameed Salih on 19 Mar 2014
Thanks for assisting me.However, your answer doesn't satisfy me since we have "for loop" here and "B,R2,m,c,t" are variables that have new values every new iteration. So that is mean the output gives me up to 20 results one by one. What I want is I need a command or may be a sentence of string that can arrange all of them in a table like the one you mentioned.This should be inside the source code. I do not want to arrange them later in the way you did because it is not practical. Again thanks for your help.
Jacob Halbrooks
Jacob Halbrooks on 19 Mar 2014
You can create an empty table before your FOR loop and then add a row of data in each iteration of the loop. For example, before the loop initialize the table with:
t = table([],[],[],[],'VariableNames', {'B','R2','m','c'});
Within your loop, your variables will get new values, which you can concatenate with t as shown below.
% Iteration 1
B = 1; R2 = 0.98463; m = 0.35271; c = 13.224;
t = [t; table(B, R2, m, c)];
% Iteration 2
B = 2; R2 = 0.96652; m = 0.26335; c = 12.687;
t = [t; table(B, R2, m, c)];

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!