Write a row and column vector as matrix index
10 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
rakesh kumar
il 24 Gen 2023
Commentato: rakesh kumar
il 24 Gen 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 Commento
Stephen23
il 24 Gen 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)
Risposta accettata
Torsten
il 24 Gen 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 Commenti
Più risposte (1)
Benjamin Kraus
il 24 Gen 2023
Modificato: Benjamin Kraus
il 24 Gen 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])
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!