How can I use two vectors of indices to get a subset of a matrix?
6 views (last 30 days)
Show older comments
Adam R Mangel
on 28 Nov 2017
Answered: Adam R Mangel
on 28 Nov 2017
Let's say I have a matrix of data that is 100 by 100 by 3 in size and I have the indices of specific locations where I want to save the data. The indices may be sequential, or completely random, or all occur in the same row...etc. How can I use my two index vectors to grab the specific values at these [row,col] pairs without using a loop? Do I need to change them to linear indices?
%%Example Code
dat = randn(100,100,3);
xind = [1 2 3 4 5 6 7 8 9 10];
zind = [2 2 2 2 2 2 2 2 2 2];
nx = numel(xind);
nz = numel(zind); % nx will always equal nz for this application
savedat = dat(zind,xind,3); % Executing this gives me a nz by nx matrix, but I want a 1 by nx(or nz) vector
What I really want is a vector like this, where j = 1:nz and i = 1:nx
[dat(zind(1),xind(1),3), dat(zind(2),xind(2),3), dat(zind(3),xind(3),3), dat(zind(j),xind(i),3)]
1 Comment
Adam
on 28 Nov 2017
To use non-contiguous multi-dimensional indexing you will generally need to convert to linear indices, yes.
doc sub2ind
Accepted Answer
Walter Roberson
on 28 Nov 2017
ind = (xind-1) * size(dat,1) + zind + (3-1) * size(dat,1) * size(dat,2);
vector = dat(ind);
The above is the internal equivalent to using sub2ind()
0 Comments
More Answers (1)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!