MATLAB: How to access part of the stucture by index

structures

Hello
I have a structure like bellow
x.part1.vector=3;
x.part1.cost=4;
x.part2.vector=5;
x.part2.cost=6;
x.part3.vector=7;
x.part3.cost=8;
I want to access value of vector on part (for example 3).
How can I access this by index?
thanks for your help

Best Answer

bkshn, try this and see if it's what you want:
% Define an array of structures.
x(1).vector=3;
x(1).cost=4;
x(2).vector=5;
x(2).cost=6;
x(3).vector=7;
x(3).cost=8;
% Access "part 3" with an index
index = 3;
output = x(index).vector
% Sum all "vector" fields for all indexes ("parts"):
outputSum = sum([x.vector])