Nested for loops to compile all possible combinations of two vectors

조회 수: 10 (최근 30일)
iontrap
iontrap 2023년 8월 14일
댓글: iontrap 2023년 8월 14일
I have two vectors and would like to acquire the result of an operation using each combination of the two arrays. The result should look something like this:
1 2 2
1 4 4
1 6 6
2 2 4
2 4 8
... etc.
if vector1 = [1 2 3 ...] and vector2 = [2 4 6 .....].
Here is my attempt:
count = 0;
for i = 1:1:I
for j = 1:1:J
%
alpha = 0.038*i - 8;
thresh = 0.00189*j + 0.01;
% perform some operation to acquire chi
chi = alpha * thresh
% save the chi into a matrix in the order of acquisition
count=count+1;
chi(:,count) = chi % this seems to give the correct 1x(I*J) array
% save all 3 columns into array for the corresponding chi. this is not working. Nearly all entries are 0.
C=zeros(I*J,3);
C(1,count) = alpha;
C(2,count) = threshold;
C(3,count) = chi;
end
count = count + J;
end

채택된 답변

Bruno Luong
Bruno Luong 2023년 8월 14일
vector1 = [1 2 3 ];
vector2 = [2 4 6 ];
[V1, V2] = meshgrid(vector1, vector2);
A = [V1(:), V2(:), V1(:).*V2(:)]
A = 9×3
1 2 2 1 4 4 1 6 6 2 2 4 2 4 8 2 6 12 3 2 6 3 4 12 3 6 18

추가 답변 (1개)

Steven Lord
Steven Lord 2023년 8월 14일
If upgrading to release R2023a or later were an option you could use the combinations function.
vector1 = [1 2 3 ];
vector2 = [2 4 6 ];
results = combinations(vector1, vector2)
results = 9×2 table
vector1 vector2 _______ _______ 1 2 1 4 1 6 2 2 2 4 2 6 3 2 3 4 3 6

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by