46 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

Sudheer Bhimireddy
on 11 Aug 2020

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

Image Analyst
on 11 Aug 2020

Stephen Cobeldick
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.

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.

your3DArray(mask) = whateverYouWant;

Image Analyst
on 11 Aug 2020

Steven Lord
on 11 Aug 2020

You can work backwards.

First, which page contains 20? It can't be the first, because that only contains linear indices 1 through 12. We know this because the size of the array in the first two dimensions is [3 4]. So we know that element 20 is at subscripts (?, ?, 2).

Now we subtract off 12 to find the linear index of the corresponding element in the first page of a matrix. Now we're trying to find the row and column indices in a 3-by-4 matrix corresponding to linear index 8. It can't be in the first column (linear indices 1-3) or the second (4-6) so we know it's in the third column, at (?, 3, 2).

We subtract off 6 to find the linear index of the corresponding element in the first column. This tells us that a linear index of 20 in a 3-by-4-by-2 array corresponds to the element at subscripts (2, 3, 2).

I've done this handwavingly, but you can formalize it using remainders (rem) as ind2sub does.

Opportunities for recent engineering grads.

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

Start Hunting!
## 0 Comments

Sign in to comment.