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 Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by