Import data as struct with fields instead of struct array (Var1, Var2...)?
조회 수: 11 (최근 30일)
이전 댓글 표시
I'm trying to import a .txt-table as a "struct with fields". For that, I use readtable() and table2struct. But MATLAB creates a struct array with the two columns Var1 and Var2. I don't want it like that but rather like in the last screenshot, which I took from a previous work of someone else. Here, the column "Field" contains the labels of the variables and column "Value" contains the corresponding values.
The difference is that the struct I create is a struct array, whereas the one from my template is just a "struct with fields".
Side note: Another problem is that the Value "test@google.com" is a NaN when I import it. Any idea how to correctly import the string?
Matlab2020b.
댓글 수: 0
채택된 답변
Ive J
2020년 12월 12일
편집: Ive J
2020년 12월 12일
Method 1:
input = readcell('input.txt').'; % read as cell, NaN won't be an issue here
inputStruct = cell2struct(input(2:end, :), input(1,:), 2); % use first row as field names
Method 2 (if you still insist in using readtable):
input = readtable('input.txt', 'ReadRowNames', true); % if still getting NaN, try setting 'TextType' to 'string'
input = rows2vars(input); % rotate the table
input.(1) = []; % discard OriginalVariableNames
inputStruct = table2struct(input, 'ToScalar', true); % a scalar struct
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!