Extract fields from struct and convert to excel file

조회 수: 11 (최근 30일)
Jonas Bender
Jonas Bender 2022년 10월 10일
편집: Eric Delgado 2022년 10월 14일
Dear community,
I create a struct with numerous fields. I simply want to extract to fields (ISPC_together & GSI together) and export a .csv list.
Any suggestions? Thanks for your support.
Jonas
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2022년 10월 10일
struct2table might be helpful (convert struct to table and save table as csv)

댓글을 달려면 로그인하십시오.

채택된 답변

Eric Delgado
Eric Delgado 2022년 10월 10일
Try this...
data = struct('ISPC_together', 0.2053, 'GSI_together', 0.0172);
data(2) = struct('ISPC_together', 0.0243, 'GSI_together', 0.0040);
writetable(struct2table(data), 'data.csv')
  댓글 수: 2
Jonas Bender
Jonas Bender 2022년 10월 14일
Dear Eric,
thank you so much for your response. Do you have an idea how to put it in a for loop. Actually I have 2 data sets. In the future it might be more. I tried the code see below and get the message
Error using struct2table (line 33) Input structure must be a scalar structure, or a structure array with one column or one row.
Kind regards, Jonas
sz = [2 2];
varTypes = {'struct', 'struct'};
varNames = {'ISPC_together', 'GSI_together'};
Table_ISPC_vs_GSI = table ('Size', sz, 'VariableNames', varNames, 'VariableTypes', varTypes);
for i = 1:numel (data)
Table_ISPC_vs_GSI(:,1) = {struct2table(data(i).ISPC_together)}
Table_ISPC_vs_GSI(:,2) = {struct2table(data(i).GSI_togehter)}
end
Eric Delgado
Eric Delgado 2022년 10월 14일
편집: Eric Delgado 2022년 10월 14일
Are you trying to concatenate the data in one just table?! See below comments on your code and something that could help you...
sz = [2 2];
varTypes = {'struct', 'struct'};
% STRUCT as elements of your big table?!
varNames = {'ISPC_together', 'GSI_together'};
Table_ISPC_vs_GSI = table ('Size', sz, 'VariableNames', varNames, 'VariableTypes', varTypes);
for i = 1:numel (data)
% data(i).ISPC_together and data(i).GSI_togehter are DOUBLE, so you can't
% convert it to TABLE using STRUCT2TABLE.
Table_ISPC_vs_GSI(:,1) = {struct2table(data(i).ISPC_together)}
Table_ISPC_vs_GSI(:,2) = {struct2table(data(i).GSI_togehter)}
end
Try this...
dataSet1 = struct('ISPC_together', 0.2053, 'GSI_together', 0.0172);
dataSet1(2) = struct('ISPC_together', 0.0243, 'GSI_together', 0.0040);
dataSet2 = struct('ISPC_together', 0.1010, 'GSI_together', 0.1010);
dataSet2(2) = struct('ISPC_together', 0.2020, 'GSI_together', 0.2020);
[struct2table(dataSet1); struct2table(dataSet2)]
ans = 4×2 table
ISPC_together GSI_together _____________ ____________ 0.2053 0.0172 0.0243 0.004 0.101 0.101 0.202 0.202

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by