# Array Building using Dynamic Field Reference using an Array of Strings

3 views (last 30 days)
Rajesh Rajaram on 10 Mar 2015
Commented: Jos (10584) on 14 Mar 2015
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.

Jos (10584) on 10 Mar 2015
Something along these lines?
Data.Field1=[1; 2; 3]
Data.Field2=[4; 5; 6]
C = struct2cell(Data)
Output = cat(2,C{:})
##### 2 CommentsShowHide 1 older comment
Jos (10584) on 14 Mar 2015
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]

James Tursa on 10 Mar 2015
>> 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
Rajesh Rajaram on 11 Mar 2015
Y'all are awesome!! Many thanks :)