Effacer les filtres
Effacer les filtres

Matlab Code: Eval and Sub2ind

2 vues (au cours des 30 derniers jours)
Wei Wen
Wei Wen le 9 Avr 2023
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

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 9 Avr 2023
Modifié(e) : Dyuman Joshi le 9 Avr 2023
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().

Plus de réponses (2)

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

Image Analyst
Image Analyst le 10 Avr 2023

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by