From: Makarand on
Hi,

I have a question about indexing into a structure. I Searched for the answer on web but wasnt successful, hence the post.

I have a structure defined as follows

global one; % define structure for body one
one.L = 1; % Half length of the body one
one.x = zeros(1,length(time)); % allocate space for x position of body one
one.y = zeros(1,length(time)); % allocate space for y position of body one
one.z = zeros(1,length(time)); % allocate space for z position of body one
one.e0 = zeros(1,length(time)); % allocate space for e0 position of body one
one.e1 = zeros(1,length(time)); % allocate space for e1 position of body one
one.e2 = zeros(1,length(time)); % allocate space for e2 position of body one
one.e3 = zeros(1,length(time)); % allocate space for e3 position of body one

As you can see except for 'L' all the other vectors of same length. I want to grab some "i"th value from each of one.x, one.y, one.z, one.e0, one.e1, one.e2, one.e3 which will give me a new vector of length 7.
I am not sure how to do this. If the question doesnt make sense or if I am missing some possible simplifications, please feel free to point out.

Thanks
Makarand
From: Walter Roberson on
Makarand wrote:

> I have a question about indexing into a structure.

Structures are not designed for the kind of indexing you want to do.

> I have a structure defined as follows

> one.L = 1; % Half length of the body one
> one.x = zeros(1,length(time)); % allocate space for x position of body one
> one.y = zeros(1,length(time)); % allocate space for y position of body one
> one.z = zeros(1,length(time)); % allocate space for z position of body one

> As you can see except for 'L' all the other vectors of same length. I
> want to grab some "i"th value from each of one.x, one.y, one.z, one.e0,
> one.e1, one.e2, one.e3 which will give me a new vector of length 7. I am
> not sure how to do this.

structfun(); or loop over the fieldnames of the structure and use
dynamic structure fieldnames; or convert the structure to a cell,
discard the first cell in the matrix, convert the resulting cell into a
matrix, and index that matrix.

fn = fieldname(one);
out = zeros(length(fn)-1,1);
outidx = 0;
for K = 1:length(fn)
if ~eq(fn{K}, 'L')
outidx = outidx + 1;
out(outidx) = one.(fn{K})[1,i];
end
end