Is there a function that returns a vector or array or list of values obtained by applying a function to margins of an array or matrix?
古いコメントを表示
For example, assume x is a vector of length n, and y is a vector of length m. I would like to construct the matrix the (n x m) matrix M(i,j) = f(x(i),y(j)). Of course I do not want to use loops!
Btw, in R, there is such a function (called apply).
採用された回答
その他の回答 (2 件)
James Tursa
2015 年 7 月 9 日
編集済み: James Tursa
2015 年 7 月 9 日
A bit clunky, but this works and makes no assumptions about f being vectorized:
n = numel(x);
m = numel(y);
M = arrayfun(@f,repmat(x(:),1,m),repmat(y(:)',n,1));
John D'Errico
2015 年 7 月 9 日
I'm surprised nobody mentioned this.
fun = @(x,y) sin(x+y);
x = 0:5;
y = (0:2:6)';
M = bsxfun(fun,x,y)
M =
0 0.84147 0.9093 0.14112 -0.7568 -0.95892
0.9093 0.14112 -0.7568 -0.95892 -0.27942 0.65699
-0.7568 -0.95892 -0.27942 0.65699 0.98936 0.41212
-0.27942 0.65699 0.98936 0.41212 -0.54402 -0.99999
3 件のコメント
James Tursa
2015 年 7 月 9 日
Good as long as fun works with column vector inputs.
John D'Errico
2015 年 7 月 10 日
Easy enough to ensure that X and Y are always the proper shapes.
M = bsxfun(fun,x(:).',y(:));
James Tursa
2015 年 7 月 10 日
編集済み: James Tursa
2015 年 7 月 10 日
I guess I wasn't clear. bsxfun passes column vectors to the function, so whatever the function is, it must be able to deal with column vector inputs (i.e., it must be vectorized to this extent). That was the only point I was trying to make. It is similar to the f(X,Y) used in IA's solution ... f must be vectorized for this to work.
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!