Robustly using ind2sub for problems with tunable dimensionality

조회 수: 3 (최근 30일)
Quentin Deplano
Quentin Deplano 2020년 11월 8일
댓글: Quentin Deplano 2020년 11월 8일
I want to find the subscripts of an element form its linear index in a n-dimensional array. So I used the code below :
(Here I take an example with 4 dimensions)
n=4 % Number of dimensions
dim=n*ones(1,n);
A=ones(dim); % Here A is a 4x4x4x4 array filled only with 1
lin_ind=240; % I define a certain linear index
A(lin_ind)=0; % I set one element of A to 0
[I,J,K,L]=ind2sub(size(A),lin_ind)
If I do this I successfuly find the subscripts for which A(I,J,K,L)=0.
But in my case, the number of dimensions is one of my input arguments. So I don't know in advance how many output arguments I need to put in the brackets for the ind2sub function. To overcome this problem I tried the code below :
% n=number of dimensions
dim=n*ones(1,n);
A=ones(dim); % Here A is an n-cubic array filled only with 1
lin_ind=240; % I define a certain linear index
A(lin_ind)=0; % I set one element of A to 0
SUB=zeros(1,n); % I preallocate n elements in a vector of length n, for all the n subscripts I'm looking for
[SUB(1:n)]=ind2sub(size(A),lin_ind)
In this way, I hoped to get all the n subscripts into the SUB vector without the requierement of knowing in advance the number of dimensions, but it turned out that this code returns an n-elements vector filled only with lin_ind (I use Matlab2017b).
Is it possible to get access to the subscripts corresponding a known linear index in an n-dimension array ?

채택된 답변

Matt J
Matt J 2020년 11월 8일
편집: Matt J 2020년 11월 8일
n=4;
dim=n*ones(1,n);
A=ones(dim); % Here A is an n-cubic array filled only with 1
lin_ind=240; % I define a certain linear index
A(lin_ind)=0; % I set one element of A to 0
[SUB{1:n}]=ind2sub(size(A),lin_ind)
SUB = 1x4 cell array
{[4]} {[4]} {[3]} {[4]}

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by