鉴于
X = [x0,x1,...,xN];
Y = [y0,y1,...,yM];
function result = f(x, y)
... % Cannot use broadcasting. Must take values. Returns a value.
end
我想得到一个矩阵
f(x0,y0) f(x0,y1) ... f(x0,yM)
f(x1,y0) f(x1,y1) ... f(x1,yM)
... ... ... ...
f(xN,y0) f(xN,y1) ... f(xN,yN)
我知道我可以使用两个嵌套的for
循环,但有没有可以并行化的东西?界面类似于arrayfun
的东西?
对于那些对f
功能感兴趣的人:
X = [some vector]
W = [some vector]
p(w) % returns a real number; for given vector, returns a vector
g(x, w) % returns value from X; can use broadcasting just like (x .* w).
function result = f(x, y) % takes 2 values from X
result = sum( p( W( g(x,W) == y ) ) );
% | | - boolean vector
% | | - vector of some values from W
% | | - vector of some real values
% | | - a single value
end
答案 0 :(得分:1)
@Matt的答案看起来比这更好,但它绝对可以与arrayfun
一起使用meshgrid
和'
来规划输入和输出的小麻烦:
X = rand(10,1);
Y = rand(5,1);
f = @(a,b) a+b;
[xx,yy] = meshgrid(X,Y);
out = arrayfun(@(a,b) f(a,b),xx,yy)';
答案 1 :(得分:0)
这样的事情应该有效。
f = @(a,b) a + b;
x = (0:10)';
y = -5:1;
res = bsxfun(f, x, y);
res =
-5 -4 -3 -2 -1 0 1
-4 -3 -2 -1 0 1 2
-3 -2 -1 0 1 2 3
-2 -1 0 1 2 3 4
-1 0 1 2 3 4 5
0 1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11
使bsxfun
工作的关键是安排输入,以便正确扩展。使用doc bsxfun
查看非单身尺寸所需的内容,以获得所需的输出。
当然,我的输出是从原始请求转换而来的,但res = res';
很容易解决。