Write a row and column vector as matrix index
14 views (last 30 days)
Show older comments
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 Comment
Stephen23
on 24 Jan 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)
Accepted Answer
Torsten
on 24 Jan 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 Comments
More Answers (1)
Benjamin Kraus
on 24 Jan 2023
Edited: Benjamin Kraus
on 24 Jan 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])
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!