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

查看:183
本文介绍了如何使用矢量化代码从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文档.尽管这并不是该功能的确切用途,但是如果您对它it之以鼻,那您所要求的正是该功能.

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天全站免登陆