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!