Accessing Elements in a 3D matrix using Linear Indexing ?

97 views (last 30 days)
Hello,
I would like to know if it is possible to access the individual element of a 3D matrix of size M*N*P using linear indexing?

Bruno Luong on 11 Aug 2020
Edited: Bruno Luong on 11 Aug 2020
Given sz = [m,n,p] ans linidx is the linear index of an element, here is one way of computing the subindexes (row, col, page). This works also for generic nd-array.
sz = [m,n,p];
tmp = linidx-1;
nd = max(length(sz),2);
subidx = zeros(1,nd);
for k=1:nd
subk = mod(tmp, sz(k));
subidx(:,k) = subk;
tmp = (tmp-subk) / sz(k);
end
subidx = subidx+1;
You can also see TMW implementation by
>> edit ind2sub
Venkata Khambhammettu on 11 Aug 2020
Thanks. This definetly helped.

Image Analyst on 11 Aug 2020
Yes, it's possible but you'd need 3 dimensions for the linear array, not 2. So not M-by-N but rows-by-columns-by-slice.
[rows, columns, slices] = size(your3DArray);
mask = whatever; % Needs to be a "rows by columns by slices" 3-D array.
Venkata Khambhammettu on 11 Aug 2020
Thanks Steven. I am pretty much looking at it like you explained to comeup with a mathematical equation to calculate all the sub-indexes.

Sudheer Bhimireddy on 11 Aug 2020
Yes, it is possible. Read this.
A = rand(10,10,10);
B = A(1:2,1:2,1:2); %<- indexing the first two values in all dimensions so it creates a 2x2x2 matrix
C = A(1,1,1); %<- indexing the first value in all dimensions so it points to a single value
Stephen on 11 Aug 2020
"So the concept of Linear Indexing doesn't work for 3D matrices ?"
Of course linear indexing works with 3D arrays, just as the documentation that I linked to clearly states: "Another method for accessing elements of an array is to use only a single index, regardless of the size or dimensions of the array. This method is known as linear indexing" (bold added).
This answer does not show any linear indexing though, so it is unrelated to your question.