Reputation: 647
I have Nx2 matrix A
and a function f
of 2 variables.
A = [1,2;3,4;5,6;7,8;9,0];
func = '@(x1, x2) sin(x1+x2)*cos(x1*x2)/(x1-x2)';
func = str2func(func);
I can apply function to matrix in a way like this:
values = arrayfun(@(x1,x2) func(x1, x2), A(:,1), A(:,2));
It seems to be faster than by for-loop
, but still to slow for my program.
I wonder if there is any other way to do it faster?
Edit. Functions are generated by the program. They are made by some simple functions like plus, minus, times, expl, ln. I don't know how to vectorize them.
Upvotes: 0
Views: 137
Reputation: 112659
The fastest approach is to vectorize your function, if that's possible. Vectorizing can sometimes be done by just changing *
, /
, ^
into their element-wise versions .*
, ./
, .^
. In other cases it may require use of bsxfun
.
For your example function, vectorization is straightforward:
A = [1,2;3,4;5,6;7,8;9,0];
x1 = A(:,1);
x2 = A(:,2);
values = sin(x1+x2).*cos(x1.*x2)./(x1-x2);
Upvotes: 1