Append character array to first row of a matrix

6 Ansichten (letzte 30 Tage)
Deepa Maheshvare
Deepa Maheshvare am 20 Mai 2020
Beantwortet: Walter Roberson am 20 Mai 2020
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 Kommentare
Deepa Maheshvare
Deepa Maheshvare am 20 Mai 2020
I tried
excelFilename = 'someFile.xlsx';
structFieldnames = fieldnames(myStruct); % <--- where myStruct is your struct of data
for k = 1:length(structFieldnames)
fieldname = structFieldnames{k};
writematrix(myheaderstruct.(fieldname), excelFilename, 'Sheet', sprintf('%s_matlab', fieldname));
writematrix(myStruct.(fieldname), excelFilename, 'Sheet', sprintf('%s_matlab', fieldname), ,'WriteMode','append');
end
I get an error:
Invalid parameter name: WriteMode.
Walter Roberson
Walter Roberson am 20 Mai 2020
Writemode is new as of R2020a.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 20 Mai 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.

Weitere Antworten (0)

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by