Matrix of two columns using two vectors

1 回表示 (過去 30 日間)
Juan Pérez Álvarez
Juan Pérez Álvarez 2022 年 2 月 12 日
Hi. I need code for coordinate points (I need the program to always create a matrix(n,2) with two columns):
For example
A = [1,2,3,4];
B = [5,6,7];
LA = length(A);
LB = length(B);
Matrix = [(1,5) ; (1,6) ; (1,7) ; (2,5) ; (2,6) ; ...];
As you can see, I need to multiply each element of vector A for each element of B. And I need to do this using for loops.
I know the Matrix has a length of LA*LB, then:
Matrix = zeros(LA*LB,2);
The question is how put every combination of the arrays to the matrix?
I reed a question in this forum to solve this kind of problem doing somethng like this:
Matrix = []
for i =1:LA
for j =1:LB
Matrix = [Matrix B]; % Something like this
end
end
¿Any idea?

採用された回答

Voss
Voss 2022 年 2 月 12 日
A = [1,2,3,4];
B = [5,6,7];
LA = length(A);
LB = length(B);
Matrix = zeros(LA*LB,2);
for i = 1:LA
for j = 1:LB
Matrix((i-1)*LB+j,:) = [A(i) B(j)];
end
end
disp(Matrix);
1 5 1 6 1 7 2 5 2 6 2 7 3 5 3 6 3 7 4 5 4 6 4 7
  2 件のコメント
Voss
Voss 2022 年 2 月 12 日
編集済み: Voss 2022 年 2 月 12 日
There are also many ways that do not use loops:
A = [1,2,3,4];
B = [5,6,7];
[A,B] = meshgrid(A,B);
Matrix = [A(:) B(:)];
disp(Matrix);
1 5 1 6 1 7 2 5 2 6 2 7 3 5 3 6 3 7 4 5 4 6 4 7
A = [1,2,3,4];
B = [5,6,7];
LA = length(A);
LB = length(B);
Matrix = [repelem(A(:),LB,1) repmat(B(:),LA,1)];
disp(Matrix);
1 5 1 6 1 7 2 5 2 6 2 7 3 5 3 6 3 7 4 5 4 6 4 7
A = [1,2,3,4];
B = [5,6,7];
LA = length(A);
LB = length(B);
Matrix = [kron(A(:),ones(LB,1)) repmat(B(:),LA,1)];
disp(Matrix);
1 5 1 6 1 7 2 5 2 6 2 7 3 5 3 6 3 7 4 5 4 6 4 7
And many others.
Juan Pérez Álvarez
Juan Pérez Álvarez 2022 年 2 月 14 日
Thank you.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by