Reputation: 7830
Let's say I have two arrays X and Y and I need a matrix M(i, j) = some_func(X(i), Y(j)). How can I get that without using loops?
Upvotes: 0
Views: 409
Reputation:
The best answer is to use bsxfun, IF it is an option. According to the help for bsxfun, it will work on any general dyadic function, as long as:
FUNC can also be a handle to any binary element-wise function not listed
above. A binary element-wise function in the form of C = FUNC(A,B)
accepts arrays A and B of arbitrary but equal size and returns output
of the same size. Each element in the output array C is the result
of an operation on the corresponding elements of A and B only. FUNC must
also support scalar expansion, such that if A or B is a scalar, C is the
result of applying the scalar to every element in the other input array.
If your function accepts only scalar input, then loops are the simple alternative.
Upvotes: 4
Reputation: 5359
It's difficult to answer your vague question, and it ultimately depends on your function. What you can do is use meshgrid
and then perform your operation, typically with use of the dot operator
e.g.
x = 1:5;
y = 1:3;
[X,Y] = meshgrid (x,y)
M = X.^Y;
Upvotes: 3