Matlab Code: Eval and Sub2ind
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Wei Wen
el 9 de Abr. de 2023
Respondida: Image Analyst
el 10 de Abr. de 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
ndim=2
idnames =',1,20'
ANS = eval(['sub2ind(ngrid.*ones(1,ndim)' idnames ');'])
0 comentarios
Respuesta aceptada
Dyuman Joshi
el 9 de Abr. de 2023
Editada: Dyuman Joshi
el 9 de Abr. de 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)
%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 comentarios
Más respuestas (2)
Walter Roberson
el 10 de Abr. de 2023
Alternate code avoiding eval():
ngrid=20;
ndim=2;
idnames = {1,20};
ANS = sub2ind(ngrid.*ones(1,ndim), idnames{:})
0 comentarios
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!