How can I write a table from a matrix?
2 views (last 30 days)
Show older comments
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
Answers (3)
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
Guillaume
on 26 Jul 2017
Edited: Guillaume
on 26 Jul 2017
You have been given two quick processes.
It creates t(10958,30891) table
So you have the table you wanted
I do not find the data
Sorry, we can't read your mind or see what you're doing. You're obviously doing something wrong or do need to learn to use matlab.
I have to write the data in table to .txt file.
Have you tried writetable ?
P=join(P1,P2)
Reading the documentation is a must. join does not just sticks two tables side by side. (that is achieved by the concatenation operator []) and is certainly not the solution you are looking for. For that matter, the documentation has plenty of examples on how to create tables. None of them use loops for that.
Walter Roberson
on 26 Jul 2017
Extract parts of it to view it, such as
t{1:2,1:10}
to see the first two rows and first 10 columns
Andrei Bobrov
on 26 Jul 2017
c = num2cell(pr,1);
TTout = timetable(datetime(year1,month1,day1),c{:});
2 Comments
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.
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.
0 Comments
See Also
Categories
Find more on Tables in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!