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?

조회 수: 1 (최근 30일)
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).

채택된 답변

Image Analyst
Image Analyst 2015년 7월 9일
Use meshgrid()
[X, Y] = meshgrid(x,y);
M = f(X, Y);
You might need to use reshape() after that to make M be 2D
M = reshape(M, m, n);
  댓글 수: 3
James Tursa
James Tursa 2015년 7월 9일
To avoid the transpose, simply reverse the initial indexing. E.g.,
[Y, X] = meshgrid(y,x);
Image Analyst
Image Analyst 2015년 7월 10일
You need to be careful. meshgrid() works on x and y, while other functions, like reshape() work on rows and columns. Note, you used x and y and said x had n columns and y had m rows. However you said that M was nxm, meaning n rows and m columns, which is the reverse. So you either made the very common mistake of thinking (rows,columns) was the same as (x,y) or you intentionally thought that your "f" function would do a transpose. Either way, you just have to be careful.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

James Tursa
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
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
John D'Errico
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
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by