Write a row and column vector as matrix index
11 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2023-1-24
"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)
采纳的回答
Torsten
2023-1-24
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 个评论
更多回答(1 个)
Benjamin Kraus
2023-1-24
编辑:Benjamin Kraus
2023-1-24
[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])
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!