Linear indices from colon operator
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Radek
el 14 de Nov. de 2024
Any array (let's consider only 2D here) can be indexed using colon operator such
array(p1:p2,p3:p4)
How can one generate list of linear indices (for that particular array) from parameters [p1, p2, p3, p4]?
0 comentarios
Respuesta aceptada
Matt J
el 14 de Nov. de 2024
[I,J]=ndgrid(p1:p2,p3:p4);
linear=sub2ind(size(array) , I,J);
0 comentarios
Más respuestas (2)
Steven Lord
el 14 de Nov. de 2024
2 comentarios
Stephen23
el 14 de Nov. de 2024
Editada: Stephen23
el 15 de Nov. de 2024
Note that in general p1:p2 and p3:p4 when used a indices like that will refer to a rectangular block of that array. So in order to get the linear indices of the entire block you will need to provide SUB2IND with subscript indices for the entire block. One way to achieve this is using NDGRID:
array = randi(9,9,9);
p1 = 3;
p2 = 5;
p3 = 2;
p4 = 5;
[X,Y] = ndgrid(p1:p2,p3:p4);
Z = sub2ind(size(array),X,Y);
array(Z)
array(p1:p2,p3:p4)
Walter Roberson
el 14 de Nov. de 2024
sub2ind() processes the indexes in parallel. All of the indices must be the same size (or else scalars)
sub2ind([4 5],1:2,1:3)
Catalytic
el 14 de Nov. de 2024
Editada: Catalytic
el 14 de Nov. de 2024
K=createArray(size(array),Fill=sparse(0));
K(p1:p2,p3:p4)=1;
out=find(K); %linear indices
1 comentario
Matt J
el 14 de Nov. de 2024
I would probably do instead,
K=createArray(size(array),Fill=sparse(false));
or maybe just use,
K=false(size(array))
depending on the expected size of the output.
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices 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!