Matlab Code: Eval and Sub2ind
6 次查看(过去 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!