MATLAB: Elegant way to extract part of a structure as an array

arraycell2matcurly bracesextracting part of a structurestructure

Hi,
I would like to be able to extract part of a structure as an array. For example, suppose I create a simple structure:
s(1).x=1;
s(1).y=2;
s(2).x=3;
s(2).y=4;
s(3).x=5;
s(3).y=6;
Now suppose I want to extract the x values for the first two parts of this structure (that is, (1).x and (2).x). So I try:
>> s([1 2]).x
ans =
1
ans =
3
I get the x values for (1) and (2), but as two separate outputs. So if I make an assignment like the following:
>> vals=s([1 2]).x
vals =
1
It only captures the first of the two outputs. I can get around this by putting the result of s([1 2]).x in a cell array, using curly braces:
>> vals={s([1 2]).x}
vals =
[1] [3]
But I actually don't want these values in a cell array; I would like them an array, with each value in a row. I can do this by the following:
>> vals=cell2mat({s([1 2]).x}')
vals =
1
3
Now I have what I want. But, my question is, is there an easier, more elegant way to do this? My conversion of the output from array to cell array and then back to array seems very convoluted.
Thanks in advance.
Andrew DeYoung
Carnegie Mellon University

Best Answer

vals = [s(1:2).x]