How to add non-row-sized variable to table?
古いコメントを表示
How can I add a variable to a table if the variable has a different length than the number of rows in the table? One reason to do this if one of the variables is a matrix, here hourlyTemperature,
nDays = 7; % Number of table rows
hoursOfDay = 6:6:24; % Vector which we wish to add
nHours = length(hoursOfDay);
hourlyTemperature = rand(nDays, nHours); % Matrix, notionally temperature measured every 6 hours for 7 days
dailyAvgWind = rand(nDays,1); % Vector, notionally daily average wind speed for 7 days
dailyAvgRain = rand(nDays,1); % Vector, notionally daily average rainfall for 7 days
% Make example table
Weather = table(dailyAvgWind, dailyAvgRain, hourlyTemperature, ...
'VariableNames', {'dailyAvgWind', 'dailyAvgRain', 'hourlyTemperature'});
I want to add hoursOfDay to the table because it is useful for interpreting hourlyTemperature. However since its length differs from the number of table rows (nDays), how do I do this?
採用された回答
その他の回答 (1 件)
Peter Perkins
2017 年 2 月 16 日
The sampling times are not "one per row", so you're either going to have to replicate them as IA suggests, or store them as metadata, either implicitly in the variable names, or explicitly.
As variable names:
>> Weather = [table(dailyAvgWind, dailyAvgRain), array2table(hourlyTemperature)];
>> Weather.Properties.VariableNames(3:end) = {'hourlyTemperature_0600' 'hourlyTemperature_1200' 'hourlyTemperature_1600' 'hourlyTemperature_2400'}
Weather =
dailyAvgWind dailyAvgRain hourlyTemperature_0600 hourlyTemperature_1200 hourlyTemperature_1600 hourlyTemperature_2400
____________ ____________ ______________________ ______________________ ______________________ ______________________
0.65548 0.82346 0.81472 0.54688 0.80028 0.035712
0.17119 0.69483 0.90579 0.95751 0.14189 0.84913
0.70605 0.3171 0.12699 0.96489 0.42176 0.93399
0.031833 0.95022 0.91338 0.15761 0.91574 0.67874
0.27692 0.034446 0.63236 0.97059 0.79221 0.75774
0.046171 0.43874 0.09754 0.95717 0.95949 0.74313
0.097132 0.38156 0.2785 0.48538 0.65574 0.39223
But presumably you stored the temps as a matrix because you want easy access to them as daily vectors. (With the above, you can get them all as a matrix using braces, i.e. Weather{:,3:end}, but having them as one matrix to begin with may be more convenient.)
As explicit metadata:
>> Weather.Properties.UserData.SamplingTimes = hours(6:6:24);
>> Weather.Properties.UserData
ans =
struct with fields:
SamplingTimes: [6 hr 12 hr 18 hr 24 hr]
By the way, in your original code, this:
'VariableNames', {'dailyAvgWind', 'dailyAvgRain', 'hourlyTemperature', 'HoursOfDay'}
was unnecessary, the table constructor would have picked up those names from the workspace variables.
1 件のコメント
カテゴリ
ヘルプ センター および File Exchange で Text Files についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!