Append character array to first row of a matrix

18 views (last 30 days)
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 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 20 May 2020
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");
end
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.

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!