필터 지우기
필터 지우기

Matlab Code: Eval and Sub2ind

조회 수: 3 (최근 30일)
Wei Wen
Wei Wen 2023년 4월 9일
답변: Image Analyst 2023년 4월 10일
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
ngrid = 20
ndim=2
ndim = 2
idnames =',1,20'
idnames = ',1,20'
ANS = eval(['sub2ind(ngrid.*ones(1,ndim)' idnames ');'])
ANS = 381

채택된 답변

Dyuman Joshi
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)
out = 6×7
1 7 13 19 25 31 37 2 8 14 20 26 32 38 3 9 15 21 27 33 39 4 10 16 22 28 34 40 5 11 17 23 29 35 41 6 12 18 24 30 36 42
%You want to find the linear index of (2,3)
%Syntax is sub2ind(sizeofthematrix,rowindex,columnindex)
ind=sub2ind(size(y),2,3)
ind = 14
%Verification
out(2,3)
ans = 14
Now
['sub2ind(ngrid.*ones(1,ndim)' idnames ');']
%updates to
['sub2ind(ngrid.*ones(1,ndim),1,20);']
%As [] is a concatenation operator
What eval() does is evaluates the string into it's equivalent mathematical form
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.
FYI - Usage of eval is generally not recommended, refer to the Note on the documentation of eval().

추가 답변 (2개)

Walter Roberson
Walter Roberson 2023년 4월 10일
Alternate code avoiding eval():
ngrid=20;
ndim=2;
idnames = {1,20};
ANS = sub2ind(ngrid.*ones(1,ndim), idnames{:})
ANS = 381

Image Analyst
Image Analyst 2023년 4월 10일

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by