如何在Matlab中对两个向量应用二进制函数以获得所有成对结果的矩阵? [英] How to apply a binary function in Matlab on two vectors to get a matrix of all pairwise results?

查看:106
本文介绍了如何在Matlab中对两个向量应用二进制函数以获得所有成对结果的矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Matlab中是否有任何函数可以接受两个向量(不一定具有相同的大小),并在向量的每一对元素上应用二进制函数,从而产生矩阵n1xn2,其中n1和n2是输入的长度向量?

Is there any function in Matlab that can take two vectors (not necessarily of the same size) and apply a binary function on every pair of the vector's elements resulting in a matrix n1xn2, where n1 and n2 are the lengths of the input vectors?

类似于pdist2的东西,但是具有任意函数指针而不是距离函数.

Something similar to pdist2, but with arbitrary function pointer instead of the distance function.

Example usage:
v1 = [1, 2, 3]
v2 = [2, 3]

Apply(@plus, v1, v2) -> [3, 4; 4, 5; 5, 6];

注意:尽管示例是数字形式,但我需要使用的实际向量是单元格数组,每个单元格包含一个字符串(所有字符串的长度均相等).二进制函数采用两个字符串并返回一个标量,例如-strcmp.

Note: although, the example is numerical, the actual vectors I need to work with are arrays of cells each containing a string (all strings have equal length). The binary function takes two strings and returns a scalar, for example - strcmp.

推荐答案

您可以使用ndgridarrayfun来实现.考虑以下示例数据(字符串的单元格数组):

You can achieve that with ndgrid and arrayfun. Consider the following example data (cell arrays of strings):

v1 = {'aa','bb','cc'};
v2 = {'1','22'};

和示例函数(字符串连接):

and example function (string concatenation):

fun = @(str1, str2) [str1 str2]

然后:

M = length(v1);
N = length(v2);
[ii jj] = ndgrid(1:M, 1:N);
reshape(arrayfun(@(k) fun(v1{ii(k)},v2{jj(k)}) , 1:M*N, 'uni', false), M,N)

获得理想的结果:

ans = 

    'aa1'    'aa22'
    'bb1'    'bb22'
    'cc1'    'cc22'

在一般情况下,只需根据需要定义v1v2fun.

In the general case, simply define v1, v2 and fun as needed.

这篇关于如何在Matlab中对两个向量应用二进制函数以获得所有成对结果的矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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