MATLAB Answers

Use NxD array of indices to reference a D dimension array in matlab

7 views (last 30 days)
M S on 8 Jan 2014
Edited: M S on 9 Jan 2014
I have a matlab matrix full of indices (indx) which can be N rows and D columns (and varies from execution to execution). I also have an output array of D dimensions, output(D1,D2,..,D_D). For a given indx, for example if D=3, a row of indx might equal (1, 2, 3), and I'd like to index output(1,2,3)=k.
However, I am not sure of two things.
1. I don't know D beforehand, how can I access a D length set of indices in output?
2. If so, is there any way accessing all ordered n-tuples in indx for each of their associated entry in output?
For 1, a remark here seems relevant: mathworks tip, specifically the part about "Indexing into an N-D array with N subscripts without knowing N ahead of time (see fftshift for an example)", except a) I'm indexing into an ND array without knowing D, and b) looking at fftshift did not help.
To be completely clear, here's some code illustrating the problem
qq(:,:,1)=[1 2; 3 4];
qq(:,:,2)=[5 6; 7 8];
indx=[1 1 1; 2 2 2] %to reference the coordinates (1,1,1)=1, and (2,2,2)=8
Thanks for looking at my question.
Edit* Sorry about qq missing the '8'.
  1 Comment
Matt J
Matt J on 8 Jan 2014
Your qq(:,:,2) does not have enough entries and produces an error message. Did you mean
qq(:,:,1)=[1 2; 3 4];
qq(:,:,2)=[5 6; 7 8];
If so, then qq(2,2,2) would not be 7, not 8.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 8 Jan 2014
Edited: Matt J on 8 Jan 2014
For your specific example
indxcell = num2cell(indx,1);
lindx = sub2ind(size(qq),indxcell{:});
result = qq(lindx)
M S on 9 Jan 2014
Matt -- any thoughts on alternatives? It seems this approach is very very inefficient. 22% of computational time of my program is spent on num2cell, and another 10% on sub2ind, and a further 10% on the actual reference. That seems ridiculous when I know the indices. Any way to avoid this?
One thing that should work would be to build indx as a cell array from the beginning, that would cut out num2cell...

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by