필터 지우기
필터 지우기

How to Convert a Scalar Struct with Vector Fields to a Vector Struct with Scalar Fields?

조회 수: 5 (최근 30일)
I have a scalar struct S with each field a row vector of the same number of elements.
S.x = [1 2];
S.y = [10 20];
I want create a struct array, A, with same number of elements as in the fields in S, with the same field names as S, where each field value in each element of A is correspondingly indexed from the original field in S. I'm not sure I'm explaining this well.
So far I have this, which works:
C = [fieldnames(s) , arrayfun(@(c) mat2cell(c{1},1,ones(1,numel(c{1}))),struct2cell(s),'Uni',false)].';
A = struct(C{:})
a = 1x2 struct array with fields:
x y
[A.x]
ans = 1x2
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[A.y]
ans = 1x2
10 20
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Open to suggestions on better (e.g., easier to understand) alternatives.

채택된 답변

Voss
Voss 2024년 4월 25일
S.x = [1 2];
S.y = [10 20];
C = [fieldnames(S) , struct2cell(structfun(@num2cell,S,'Uni',false))].';
A = struct(C{:})
A = 1x2 struct array with fields:
x y
[A.x]
ans = 1x2
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[A.y]
ans = 1x2
10 20
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

추가 답변 (2개)

Voss
Voss 2024년 4월 25일
S.x = [1 2];
S.y = [10 20];
C = [fieldnames(S) , cellfun(@num2cell,struct2cell(S),'Uni',false)].';
A = struct(C{:})
A = 1x2 struct array with fields:
x y
[A.x]
ans = 1x2
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[A.y]
ans = 1x2
10 20
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Voss
Voss 2024년 4월 25일
S.x = [1 2];
S.y = [10 20];
N = numel(S.x);
f = fieldnames(S);
NF = numel(f);
clear A
A(N) = S;
for ii = 1:N
for jj = 1:NF
A(ii).(f{jj}) = S.(f{jj})(ii);
end
end
A
A = 1x2 struct array with fields:
x y
[A.x]
ans = 1x2
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[A.y]
ans = 1x2
10 20
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

카테고리

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

태그

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by