简体   繁体   中英

String Header for data Matlab

I found "Adding a header to a matrix in Matlab" question which was very close to what I need done. I was hoping to keep the data in the cells, since my headers are large and i'm running this multiple times I dont want to use file io since it adds tons of time.

this is what i have...

  • header = ( 'Quarter', 'monthly amount remaining', 'annual amountremaining');

    data =

      1 30000 150000 2 20000 130000 

and i can't seem to get this

out = 

  Quarter    monthly am    annual am
        1         30000       150000

        2         20000      130000

It's very frustrating, i've tried num2str, and a bunch of other stuff... i'm going to try num2cell and just make a big array and fill them in... well happy friday, i'm heading home T_T

If you have access to the Statistics Toolbox, you can create a dataset array

header = {'Quarter', 'monthly amount remaining', 'annual amountremaining'}
data =    [ 1        30000    150000;
    2        20000    130000];

ds = dataset({data,header{:}})

ds = 

    Quarter    monthlyAmountRemaining    annualAmountremaining
    1          30000                     1.5e+05              
    2          20000                     1.3e+05  

Note that this removes the spaces in your header names, but with the dataset, you can then use these names to conveniently access the columns, such as:

>> ds.Quarter

ans =

     1
     2

If you just want to write to Excel (and not use the dataset methods), you can create a single cell array:

 [header;num2cell(data)]

ans = 

    'Quarter'    'monthly amount remaining'    'annual amountremaining'
    [      1]    [                   30000]    [                150000]
    [      2]    [                   20000]    [                130000]

As far as I am aware there is no true built in support for that. Related to what Xurtio mentioned, you're wanting to do in reverse what Matlab undoes when it performs an xlsread. Their solution is to create a matrix for the numbers (which have a fixed size and are therefore amenable to array style indexing), and a cell array for the strings which have a variable size.

The following is pretty much from the disp() Matlab docs and it accomplishes the effect, but not in a flexible way:

header='        Quarter  MonthlyAM   AnnualAM  ';
data=[1 30000 150000; 2 20000 130000];
disp(header);
disp(data);
    Quarter  MonthlyAM   AnnualAM  
       1       30000      150000
       2       20000      130000

If you want to achieve more flexible formatting, you could look into an sprintf intermediary for the data matrix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM