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!