MATLAB: how to multiply a multidimensional matrix using one-dimensional vector indices without loops?
I am currently looking for an efficient way to slice up multidimensional matrices in MATLAB. For example, for example, I have a multidimensional matrix such as
A = rand(10,10,10)
I would like to get a subset of this matrix (let's call it B
) at some indices along each dimension. To do this, I have access to the index vectors along each dimension:
ind_1 = [1,4,5]
ind_2 = [1,2]
ind_3 = [1,2]
Right now I'm doing it rather inefficiently like this:
N1 = length(ind_1)
N2 = length(ind_2)
N3 = length(ind_3)
B = NaN(N1,N2,N3)
for i = 1:N1
for j = 1:N2
for k = 1:N3
B(i,j,k) = A(ind_1(i),ind_2(j),ind_3(k))
end
end
end
I suspect there is a smarter way to do this. Ideally I am looking for a solution that is not used for loops and can be used for an arbitrary dimensional matrix N
.
source to share
It's actually very simple:
B = A(ind_1, ind_2, ind_3);
As you can see Matlab indices can be vectors and then the result is the Cartesian product of those vector indices. More information on Matlab indexing can be found here .
If the number of dimensions is unknown during programming, you can define the indices in the core of the cell and then expand into a comma separated list :
ind = {[1 4 5], [1 2], [1 2]};
B = A(ind{:});
source to share
You can refer to data in matrices simply by specifying indices, as in the following example:
B = A(start:stop, :, 2);
In the example:
-
start:stop
gets a range of data between two points -
:
gets all records -
2
only gets one record
In your case, since all your indices are 1D, you can simply use:
C = A(x_index, y_index, z_index);
source to share