3

Assume I have a structure called I of the size n*1, with a multiple fields one of which is called 'area' for example. When I try the code below:

area = I.area

the resultant area only have the one value that comes from the last position of the structure. Is there any fast way to exact all the values in the field, except using for loop as follows:

for ii = 1:n; area(ii) = I(ii).area; end
Suever
  • 64,497
  • 14
  • 82
  • 101
jwm
  • 4,832
  • 10
  • 46
  • 78

2 Answers2

1
area = [I.area]

I.area returns all values of I(1).area, I(2).area ... as a comma-separated list, which can be plugged into wherever such list is expected, e.g. function parameter list or array initialization.

EDIT: If all I(i).area is a row vector with equal size. Then you can first concatenate all of them horizontally, then reshape to desired dimension:

area =  reshape([I.area], [2 length(I)])'

Result:

>> I.area

ans =

     3     4


ans =

     5     6


ans =

     7     8

>> reshape([I.area], [2 length(I)])'

ans =

     3     4
     5     6
     7     8
Mingjing Zhang
  • 943
  • 5
  • 11
  • It works if the area field has one value in each position, such as I(1).area = 1. What if the entry has two value I(1).area = [1, 2]? Is it possible to extract these values just as they are structured as a matrix rather than shaped into a column or a row. For example: – jwm Sep 24 '16 at 11:59
  • If I(1).area = [1, 2], I(2).area = [3, 4], I want the output is [1, 2; 3, 4]. – jwm Sep 24 '16 at 12:10
  • If your intention is to address cases where `area` is a 2x1 vector, please say so explicitly in your question next time so that answerers do not have to guess what you really mean. And this line `area(ii) = I(ii).area;` strongly suggests `I.area` is a scalar, Anyway, a vector `area` can be easily handled with `reshape`. I've edited my answer to reflect that. – Mingjing Zhang Sep 24 '16 at 17:04
1

Using simple [] around the struct will result in horizontal concatenation of all values. If you instead want to concatenate them along another dimension, you can use cat to specify this explicitly. This will allow you to better handle fields which may contain multiple values.

% Concatenate them along the first dimension
out = cat(1, I.area);

% Concatenate them along the third dimension
out = cat(2, I.area);

Alternately, if the fields are all different dimensions, then turn them into a cell

out = {I.area};
Suever
  • 64,497
  • 14
  • 82
  • 101