How can I write a table from a matrix?

4 views (last 30 days)
Szabó-Takács Beáta
Szabó-Takács Beáta on 26 Jul 2017
Answered: Peter Perkins on 26 Jul 2017
Dear All, I have a matrix pr(10958,30888) and three vectors year(10958,1), month(10958,1) and day(10958,1). I would like to create a table(10958,30892) from these. I tried the following way:
for i=1:30888
P=table(year,month,day,pr(:,i));
end
but it created a table what had only 4 column (year,month,day,var1). Can someone suggest me a solution? Thank you for your help in advance!
  1 Comment
Andrei Bobrov
Andrei Bobrov on 26 Jul 2017
Hi Beáta!
Please attach small part of the your data.

Sign in to comment.

Answers (3)

Walter Roberson
Walter Roberson on 26 Jul 2017
t = array2table([year, month, day, pr]);
t.Properties.VariableNames(1:3) = {'year','month','day'};
t.Properties.VariableNames(4:end) = cellstr(num2str((1:size(pr,2))','pr%d'));
  4 Comments
Walter Roberson
Walter Roberson on 26 Jul 2017
summary(t) to get an overview of it; https://www.mathworks.com/help/matlab/ref/summary.html
Extract parts of it to view it, such as
t{1:2,1:10}
to see the first two rows and first 10 columns

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 26 Jul 2017
c = num2cell(pr,1);
TTout = timetable(datetime(year1,month1,day1),c{:});
  2 Comments
Guillaume
Guillaume on 26 Jul 2017
"unfortunately it does not work"
There may be many reason for why it doesn't work. One of them could be that you're on an older version of matlab which does not have timetable.
Rather than letting us guess, give us the error message or the reason why it does not work. It does not work is totally unhelpful.

Sign in to comment.


Peter Perkins
Peter Perkins on 26 Jul 2017
Perhaps the most straight-forward thing to use to get a table with 30891(=30888+3) variables in it would be
t = [table(year,month,day) array2table(pr)]
but I would question the usefulness of a table with that many variables. It works, but is it useful?
What about
t = table(year,month,day,pr)
which creates a table with four variables, one of which itself has 30888 columns.
And as Andrei said, a timetable might be the way to go if you have R2016b or later. Of course, if you are just using the table to write to a file via writetable, then you don't need a timetable. You could still convert day,month,year into a datetime so your file has one column in it, that's up to you.

Products

Community Treasure Hunt

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

Start Hunting!