适用bsxfun或arrayfun到矩阵中的每一行 [英] apply bsxfun or arrayfun to every row of a matrix

查看:162
本文介绍了适用bsxfun或arrayfun到矩阵中的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个矩阵, A B 与大小 M -by-4和 N 逐4分别。我的问题是如何将一个函数˚F,它有两个1×4向量作为输入,A和B的每一行的结果将与大小<$ C矩阵$ C> M X N 。 ))结果是 F(A(I,:),B(J,元素[I,J] C>。

There are two matrices, A and B with size m-by-4 and n-by-4 respectively. My question is how to apply a function f, which takes two 1x4 vectors as input, on every row of A and B. The result will be a matrix with size mxn. The element [i, j] in result is f(A(i, :), B(j, :)).

例如:

A = rand(3, 4);
B = rand(5, 4);
for i = 1 : 3
    for j = 1 : 5
        result(i, j) = rectint(A(i, :), B(j, :));
    end
end

我可以使用 bsxfun arrayfun 来做好这项工作?

推荐答案

您可以使用 arrayfun ,如果你第一次使用 meshgrid 生成行的所有组合:

You can use arrayfun, if you first use meshgrid to generate all combinations of rows:

[ii jj] = meshgrid(1:size(A,1),1:size(B,1));
result = arrayfun(@(n) rectint( A(ii(n),:), B(jj(n),:) ), 1:numel(ii) );
result = reshape(result, size(B,1), size(A,1)).';

您当然可以替代的 rectint 通过接受两个向量输入,并返回一个数字。任何其他函数

You could of course substitute rectint by any other function that accepts two vector inputs and returns a number.

这篇关于适用bsxfun或arrayfun到矩阵中的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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