如何使用向量化代码从 MATLAB 中的两个向量生成所有对? [英] How to generate all pairs from two vectors in MATLAB using vectorised code?

查看:32
本文介绍了如何使用向量化代码从 MATLAB 中的两个向量生成所有对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我不止一次需要在 MATLAB 中生成所有可能的两个向量对,我使用 for 循环来完成,这些循环占用了相当多的代码行,即

More than once now I have needed to generate all possible pairs of two vectors in MATLAB which I do with for loops which take up a fair few lines of code i.e.

vec1 = 1:4;
vec2 = 1:3;
i = 0;
pairs = zeros([4*3 2]);
for val1 = vec1
    for val2 = vec2
         i = i + 1;
         pairs(i,1) = val1;
         pairs(i,2) = val2;
    end
end

生成...

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1 
4 2
4 3

一定有更好的方法来做到这一点,更像 MATLAB 吗?

There must be a better way to do this which is more MATLAB'esque?

n.b.nchoosek 不做我需要的反向对(即 2 1 以及 1 2),我不能只是反向并附加 nchoosek 输出,因为对称对将被包含两次.

n.b. nchoosek does not do the reversed pairs which is what I need (i.e. 2 1 as well as 1 2), I can't just reverse and append the nchoosek output because the symmetric pairs will be included twice.

推荐答案

尝试

[p,q] = meshgrid(vec1, vec2);
pairs = [p(:) q(:)];

请参阅 MESHGRID 文档.虽然这不完全是该功能的用途,但如果你眯着眼睛看它很有趣,你所要求的正是它的作用.

See the MESHGRID documentation. Although this is not exactly what that function is for, but if you squint at it funny, what you are asking for is exactly what it does.

这篇关于如何使用向量化代码从 MATLAB 中的两个向量生成所有对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆