Write a row and column vector as matrix index
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
rakesh kumar
el 24 de En. de 2023
Comentada: rakesh kumar
el 24 de En. de 2023
I want to write a row vector [4 5 3] and column vector [4 5 3]' as (4, 4) (4,5) 4, 3) (5, 4) (5, 5) (5, 3) (3, 4) (3, 5) and (3, 3) so that i can use it as index of a matrix.
1 comentario
Stephen23
el 24 de En. de 2023
"I want to write a row vector [4 5 3] and column vector [4 5 3]' as (4, 4) (4,5) 4, 3) (5, 4) (5, 5) (5, 3) (3, 4) (3, 5) and (3, 3) so that i can use it as index of a matrix."
Why do you need to "write" it like that to "use it as index of a matrix" ?
You can use those numeric vectors directly as indices:
A = rand(5,5)
X1 = [4,5,3];
X2 = [4,5,3];
B = A(X1,X2)
Respuesta aceptada
Torsten
el 24 de En. de 2023
a = [4 5 3];
% Generate index vectors A and B
[A,B] = ndgrid(a,a);
A = A(:)
B = B(:)
% Use A and B as index vectors for a matrix M
M = rand(10)
S = M(sub2ind([10 10],A,B))
0 comentarios
Más respuestas (1)
Benjamin Kraus
el 24 de En. de 2023
Editada: Benjamin Kraus
el 24 de En. de 2023
[X,Y] = meshgrid([4 5 3],[4 5 3])
[X,Y] = ndgrid([4 5 3],[4 5 3])
After calling either meshgrid or ndgrid you can then convert those matrices into vectors, although that isn't needed.
[X,Y] = meshgrid([4 5 3],[4 5 3]);
X = X(:);
Y = Y(:);
[X Y]
Both meshgrid and ndgrid do the same thing, but they swap the orientation of the first two dimensions. meshgrid works with "X" (the first input/output) along the columns and "Y" (the second input/output) along the rows. ndgrid works with "X" (the first input/output) along the rows, and "Y" (the second input/output) along the columns. It may help to understand the behavior of meshgrid and ndgrid (and the difference), if you use different vectors for the inputs, so for the sake of comparing the two:
[X,Y] = meshgrid(1:3,4:6)
[X,Y] = ndgrid(1:3,4:6)
Also, if the first two inputs are the same, you can use a shortcut and just provide one input:
[X,Y] = meshgrid([4 5 3])
[X,Y] = ndgrid([4 5 3])
Ver también
Categorías
Más información sobre Multidimensional 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!