Append character array to first row of a matrix

조회 수: 4 (최근 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
Deepa Maheshvare
Deepa Maheshvare 2020년 5월 20일
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 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");
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by