ind2sub with arbitrary martix
이전 댓글 표시
Hi
I intend to use ind2sub to get the subscripts indexing from linear indexing and I will use if to read data in matrix of arbitrary size.
The problem with this is that you have to know the dimension of the matrix, so that you can call ind2sub with the corresponding number of outputs. What I would like is to get a output vector that has the corresponding number of elements. Is this possible to achieve?
Best regards
Thomas
채택된 답변
추가 답변 (3개)
You mean
A = rand(5,6);
s = size(A)
?
댓글 수: 2
Torsten
2023년 2월 16일
I don't know how you automativcally get I according to the matrix size. I asked this question below. I think @Steven Lord will be able to answer this.
Use size(M) as the size argument to ind2sub where M is the matrix...the size argument doesn't have to be a constant expression.
You have to specify the size of the array you want to use the subscripts to index into because the same linear index could generate different subscripts based on the size. Consider two examples where I want the subscripts for element 4.
A1 = reshape(1:8, 2, 4)
A2 = reshape(1:8, 4, 2)
A1 and A2 have the same number of elements but different sizes. This means that element 4 of A1 is element (2, 2) and element 4 of A2 is element (4, 1).
[r1, c1] = ind2sub(size(A1), 4)
[r2, c2] = ind2sub(size(A2), 4)
If I just called ind2sub with the input 4, should the outputs be 2 and 2, 4 and 1, or something else?
But let's take a step back. When you say this:
What I would like is to get a output vector that has the corresponding number of elements.
do you just want to use linear indexing? How are you hoping or planning to use these indices with a "matrix of arbitrary size"?
B1 = A1.^2 % just so the elements aren't 1:8
B2 = A2.^2
[B1(4) B2(4)] % Both are 16
댓글 수: 1
Say I have a matrix A I don't know the size of in advance.
How can I prescribe that the array of outputs I1,I2,...In from ind2sub as
matches the number of dimensions of A ?
In the example below: how to set the three output arguments [I1 I2 I3] "automatically" ?
A = rand(3,6,34);
s = size(A);
[I1 I2 I3] = ind2sub(s,24)
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!