MATLAB: How to use two vectors of indices to get a subset of a matrix

indexingmatrices

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)]

Best Answer

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()