Array Building using Dynamic Field Reference using an Array of Strings

조회 수: 1 (최근 30일)
This is an example of what I am trying to do: Data.Field1=[1; 2; 3];
Data.Field2=[4; 5; 6];
Output=Data.({'Field1'; 'Field2'}) - I know this gives an error, but I want to do something similar
Answer (Desired) Output= [1 4; 2 5; 3 6]
I know I can do it using a for loop for field and build the Output. I was wondering if there is a more elegant way to it.
Many thanks in advance

채택된 답변

Jos (10584)
Jos (10584) 2015년 3월 10일
Something along these lines?
Data.Field1=[1; 2; 3]
Data.Field2=[4; 5; 6]
C = struct2cell(Data)
Output = cat(2,C{:})
  댓글 수: 2
Rajesh Rajaram
Rajesh Rajaram 2015년 3월 10일
편집: Rajesh Rajaram 2015년 3월 10일
This is awesome!! Thank you. This definitely answers my initial question.
I have a follow up question: What if Data had a lot more fields say Field001...Field100 and I want to collate only some of the fields into an array?
Req_Field = {'Field001'; 'Field010'; 'Field011'..'Field030'}
- this list could change in the future and hence don't want to hard code each field name in my extraction
Thanks again
Jos (10584)
Jos (10584) 2015년 3월 14일
Do not set up your data structure like that. Use arrays:
Data.Field(1).values = [1 2 3]
Data.Field(2).values = [4 5 6]

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

추가 답변 (1개)

James Tursa
James Tursa 2015년 3월 10일
>> Data.Field1 = [1;2;3]
Data =
Field1: [3x1 double]
>> Data.Field2 = [4;5;6]
Data =
Field1: [3x1 double]
Field2: [3x1 double]
>> Data.Field3 = 1:4
Data =
Field1: [3x1 double]
Field2: [3x1 double]
Field3: [1 2 3 4]
>> Fields = {'Field1','Field2'}
Fields =
'Field1' 'Field2'
>> n = numel(Fields)
n =
2
>> f = @(y,x)(y.(x))
f =
@(y,x)(y.(x))
>> Datas = cell(1,n);
>> Datas(:) = {Data}
Datas =
[1x1 struct] [1x1 struct]
>> cell2mat(cellfun(f,Datas,Fields,'UniformOutput',false))
ans =
1 4
2 5
3 6

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by