Append character array to first row of a matrix

21 ビュー (過去 30 日間)
Deepa Maheshvare
Deepa Maheshvare 2020 年 5 月 20 日
回答済み: Walter Roberson 2020 年 5 月 20 日
Hi there!
I've the following struct array
Astruct =
struct with fields:
data1: [10×5 double]
data2: [10×5 double]
I would like to append a column header to the values stored in the above-metnioned struct before writing to an excel sheet.
data1_header = [1,3,2,4,5];
data2_header = [1,2,3,4,10];
Astruct =
struct with fields:
data1: [10×5 double] % header 'col' + data1_header : ['col1','col3','col2','col4','col5'];
data2: [10×5 double] % ['col1','col2','col3','col4','col10']
Any suggestions on how to do the above will be of great help
  4 件のコメント
Walter Roberson
Walter Roberson 2020 年 5 月 20 日
Writemode is new as of R2020a.



Walter Roberson
Walter Roberson 2020 年 5 月 20 日
Astruct = struct('data1', randi(9,10,5), 'data2', randi(9,10,5))
data1_header = [1,3,2,4,5];
data2_header = [1,2,3,4,10];
C = [ cellstr([ "col" + data1_header, "col" + data2_header])
table2cell(splitvars(struct2table(V))) ];
writecell(C, excelFilename)
This assumes that you want them to go onto the same sheet. If you want different sheets then
Astruct = struct('data1', randi(9,10,5), 'data2', randi(9,10,5));
data1_header = [1,3,2,4,5];
data2_header = [1,2,3,4,10];
data_headers = {data1_header, data2_header};
data_contents = structfun(@(M) {num2cell(M)}, Astruct);
F = fieldnames(Astruct);
for K = 1 : length(F)
C = [ cellstr("col" + data_headers{K});
data_contents{K} ];
writecell(C, excelFilename, 'Sheet', F{K} + "_matlab");
I tested, and this does create multiple sheets in the file.
What it will not do is put the data on the bottom of any existing sheet with the same name. If you want that, then you need to readcell() the existing sheet, append that at the top, and write the combination. Watch out for the possibility that the number of columns is different between the existing data and the new data.

その他の回答 (0 件)




Community Treasure Hunt

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

Start Hunting!

Translated by