0

I want to extract items from multiple fields of a structure and put them in an array with unique applied.

Say the structure has this format:

A=repmat( struct('field1',[],'field2',[],'field3',[]) ,100,1);

To extract unique field 1 and field2 I can write this:

[a ia iar]=unique([A(:).field1]);
b=[A(:).field2];
b=b(ia);

I would like to write something like this:

[a ia iar]=unique([A(:).field1]);
b=[A(:).field2](ia);

But Matlab (2012a) doesn't seem to allow accessing items in an array at the time of declaration although the array can be passed to a function without a problem. Is there a way to do this?

Thanks,

David

1 Answers1

0

Although plain MATLAB syntax does NOT support nested indexing of intermediate results, there are many ways around as pointed out in the comment by EitanT.

However, in your case you do not need those as shown in the example below. You can index the non-scalar structure:

% Example input and unique according to 'field1'
A       = struct('field1',num2cell(randi(20,100,1)),'field2',num2cell(randi(20,100,1)));
[~, ia] = unique([A(:).field1]);

% First assign
b1 = [A(:).field2];
b1 = b1(ia);

% Select directly
b2 = [A(ia).field2];

isequal(b1,b2) %ok
Oleg
  • 10,406
  • 3
  • 29
  • 57