Multi indexing question on structured array

1 view (last 30 days)
Peter Leoni
Peter Leoni on 13 Aug 2015
Edited: Stephen23 on 14 Aug 2015
I have an array
a(1).data=rand(3,1); a(2).data=rand(4,1) ; a(3).data = rand(5,1) ; a(4).data = rand(5,1)
and a vector of the same length as the struct array a
idx = [ 2, 2, 5, 1]
and I would like to basically get
[ a(1).data(idx(1)), a(2).data(idx(2)), a(3).data(idx(3)), a(4).data(idx(4)) ]
how do I do this in 1 line?
thanks for the help

Answers (1)

Steven Lord
Steven Lord on 13 Aug 2015
You just did.
[ a(1).data(idx(1)), a(2).data(idx(2)), a(3).data(idx(3)), a(4).data(idx(4)) ]
If you're looking for something that generalizes to any struct array and an idx vector of compatible size, the easiest way would be to use a FOR loop. Preallocate your output then loop over 1:numel(idx) and store the result of the indexing operation into the appropriate element of the output. ["FOR loop" is NOT a "dirty word" in MATLAB. When used appropriately, a FOR loop can be a useful tool. When misused, it can be detrimental to your code's performance and/or readability, but so can any tool.]
  2 Comments
Peter Leoni
Peter Leoni on 14 Aug 2015
I dont like for loops, so always looking to not use them...
I did find a way by building up the expression as a string and then using eval but i am sure there is a faster way
Stephen23
Stephen23 on 14 Aug 2015
Edited: Stephen23 on 14 Aug 2015
Using a for loop is much more preferable to using eval. Don't use slow, buggy and obfuscated code with eval when you can use a simple, fast and reliable for loop (and some array preallocation).

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!