Robustly using ind2sub for problems with tunable dimensionality
조회 수: 3 (최근 30일)
이전 댓글 표시
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 ?
댓글 수: 0
채택된 답변
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!