Robustly using ind2sub for problems with tunable dimensionality
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Quentin Deplano
el 8 de Nov. de 2020
Comentada: Quentin Deplano
el 8 de Nov. de 2020
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 comentarios
Respuesta aceptada
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!