是否有类似 arrayfun 的东西,但适用于多个维度?
Is there something like arrayfun, but for multiple dimensions?
给定
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
像这样的东西应该有用。
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';
解决。
@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)';
给定
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
像这样的东西应该有用。
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';
解决。
@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)';