user1641496
user1641496

Reputation: 457

in Matlab, get field values in structs

Sorry if the question has been asked before, can't find searching. I have an array of structures (about a 1000). Each struct has a field called "travelTime" which is a 3D matrix of size "120x92x150". I need to look up the value for a certain position for all 1000 matrices, for ex. index (60,46,75) so I would have an array with 1000 elements. I could do it in a for loop, but is there an easier and more elegant way (faster)?

Thanks, Kamran

Upvotes: 2

Views: 2083

Answers (2)

Eitan T
Eitan T

Reputation: 32920

Concatenate everything along a fourth dimension, retrieve all indices and then squeeze the result back into a column vector. For example, if your structure array is S, you can do this:

A = cat(4, S.travelTime);
points = squeeze(A(60, 46, 75, :));

Benchmarking

Let's benchmark the possible solutions:

M = reshape(1:18, 2, 3, 3);
for k = 1:100
    s(k).travelTime = mod(k, 6) * M;
end

tries = 1e4;

%// Vectorized solution
tic
for jj = 1:tries
    A = cat(4, s.travelTime);
    points = squeeze(A(1, 2, 1, :));
end
toc

%// For loop solution
tic
for jj = 1:tries
    points = zeros(size(s));
    for ii = 1:numel(s)
        points(ii) = s(ii).travelTime(1, 2, 1);
    end
end
toc

%// arrayfun solution
tic
for jj = 1:tries
    Points = arrayfun(@(ii)s(ii).travelTime(1, 2, 1), 1:numel(s));
end
toc

The results are:

Elapsed time is 0.072367 seconds.
Elapsed time is 0.890323 seconds.
Elapsed time is 1.08522 seconds.

Not surprisingly, the vectorized solution is the fastest and an arrayfun solution is the slowest.

Upvotes: 4

Hugh Nolan
Hugh Nolan

Reputation: 2519

To copy a nice answer from In Matlab, how can I sort the order of a nested structure? (thanks @Gunther-Struyf!):

Points = arrayfun(@(ii) myStruct(ii).travelTime(60,46,75),1:numel(myStruct));

Upvotes: 3

Related Questions