Formatting data from an excel sheet in MATLAB

半腔热情 提交于 2019-12-20 03:01:17

问题


I import data from an excel file using the command xlsread. The data look like the following:

I would like to format these data so that the output looks like:

A = [NaN 1 2 3; 
    20160101 100 80 90; 
    20170101 150 90 200]

In excel, I would use a Pivot table. Is there an equivalent in MATLAB or how would I start to code this? Is reshape an option here?


回答1:


I'll assume you are reading your data from the file as follows:

data = xlsread('your_file.xls');

Which gives you a numeric matrix containing your data. You can then reorganize it by parsing your first and last columns using unique, then using the results as indices into accumarray to collect the data in the center column. Then you just add the row and column labels:

[rowVals, ~, rowIndex] = unique(data(:, 3));
[colVals, ~, colIndex] = unique(data(:, 1).');
A = accumarray([rowIndex colIndex], data(:, 2));
A = [NaN colVals; rowVals A];

And the result, for your sample data above:

A =

         NaN           1           2           3
    20160101         100          80         200
    20170101         150          90         200

If you have duplicate entries (i.e. entries that have the same date and identifier), the above will sum them by default. You can provide a function handle to accumarray if you'd like it to do something else. For example:

A = accumarray([rowIndex colIndex], data(:, 2), [], @mean);      % Averages them
A = accumarray([rowIndex colIndex], data(:, 2), [], @(x) x(1));  % Keeps the first entry


来源:https://stackoverflow.com/questions/47209419/formatting-data-from-an-excel-sheet-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!