Convert subscripts to linear indices with dynamic matrix size

조회 수: 2 (최근 30일)
Soan Duong
Soan Duong 2020년 8월 6일
댓글: Gaurav Garg 2020년 8월 10일
Hi all,
I have a matrix with a dynamic size, e.g. M x N. Each row of the matrix indicates subscripts of an element in a N-D matrix.
Do you know how to convert the subscript matrix into a linear index vector without listing the subscripts of every dimension as in sub2ind function?
Thanks!

채택된 답변

Bruno Luong
Bruno Luong 2020년 8월 10일
편집: Bruno Luong 2020년 8월 10일
% Generate random array of nd-indexes
sz=[3 4 5 6];
m = 10;
n = length(sz);
SUBIDX=ceil(sz.*rand(m,n));
% Method 1, with sub2ind
LINIDX1 = zeros(m,1);
for k=1:size(SUBIDX,1)
subidxk = num2cell(SUBIDX(k,:));
LINIDX1(k) = sub2ind(sz,subidxk{:});
end
LINIDX1
% Method 2, not using sub2ind, NOTE: no error check for overflow
p = cumprod([1 sz(1:end-1)]);
LINIDX2 = (SUBIDX-1)*p(:)+1
% Method 3, for-loop on dimension
LINIDX3 = 0;
for k=n:-1:1
LINIDX3 = LINIDX3 * sz(k) + (SUBIDX(:,k)-1);
end
LINIDX3 = LINIDX3 + 1
  댓글 수: 1
Soan Duong
Soan Duong 2020년 8월 10일
Thanks, @Bruno Luong.
Your answers are awesome. That is exactly what I need.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Gaurav Garg
Gaurav Garg 2020년 8월 10일
편집: Gaurav Garg 2020년 8월 10일
Hi Soan,
You can loop over all the rows, which indicate subscripts and run sub2ind function; and store the results in an array.
  댓글 수: 2
Soan Duong
Soan Duong 2020년 8월 10일
Thanks, @Gaurav.
I did as your answer. Just wonderring whether there is any optimized method instead :).
Gaurav Garg
Gaurav Garg 2020년 8월 10일
Soan,
Instead of using the ind2sub function, you can convert N-D array index to 1-D index. I would provide you with an example for N=2 -
For a 2-D array of dimensions M x N and an element A(i,j) in it-
A(i,j) = (j-1) * N + i
Since MATLAB stores data in column-major format, you would skip (j-1) columns resulting to (j-1)*N elements and ith element from here would be your resultant array.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by