Matlab Code: Eval and Sub2ind
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi, I come through this code and i couldn't understand how it works.
It is combination of eval and sub2ind. Could anybody explain to me with this problem. How to get the final answer = 381?
Thanks in advance.
Problem
ngrid=20
ndim=2
idnames =',1,20'
ANS = eval(['sub2ind(ngrid.*ones(1,ndim)' idnames ');'])
댓글 수: 0
채택된 답변
Dyuman Joshi
2023년 4월 9일
편집: Dyuman Joshi
2023년 4월 9일
sub2ind() converts subscripts to linear indices.
Say for example, you have a mxn matrix, and you want to find the linear index of (i,j)th element (given i<=m, j<=n). (Linear indexing in MATLAB is done column wise.) sub2ind() will be useful for that
%Random values
m=randi(7);
n=randi(7);
y=rand(m,n);
%As stated above, an example of Linear indexing
out=reshape(1:m*n,m,n)
%You want to find the linear index of (2,3)
%Syntax is sub2ind(sizeofthematrix,rowindex,columnindex)
ind=sub2ind(size(y),2,3)
%Verification
out(2,3)
Now
['sub2ind(ngrid.*ones(1,ndim)' idnames ');']
%updates to
['sub2ind(ngrid.*ones(1,ndim),1,20);']
%As [] is a concatenation operator
so
x=3;y=2;z=1;
eval('x+y-z')
%is equivalent to
x+y-z
%In terms of the above example, it is equivalent to
sub2ind(ngrid.*ones(1,ndim),1,20)
%which is equal to
sub2ind(20.*[1 1],1,20)
%i.e. the linear index of (1,20) in a 20x20 matrix,
%and thus you get the value 381
Hope this is helpful.
댓글 수: 0
추가 답변 (2개)
Walter Roberson
2023년 4월 10일
Alternate code avoiding eval():
ngrid=20;
ndim=2;
idnames = {1,20};
ANS = sub2ind(ngrid.*ones(1,ndim), idnames{:})
댓글 수: 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!