Suppose I have a function
and that I'm interested in running over a grid of values of q and w. Here is my code in MATLAB:
clc; clear;
qlength = 1000;
wlength = 100;
qvec = rand(qlength,1);
wvec = rand(wlength,1);
[wgrid,qgrid] = meshgrid(wvec,qvec);
f = @(w,q)(1+exp(-q^2*w^2)*w*(1+w*q^2));
results = f(wgrid,qgrid);
If you run it, you will find that the last line returns an error. I have 2 remedies: two nested loops and arrayfun
. The loops make the code ugly and the arrayfun
is actually slower than the loops. How can I rewrite the definition of f
above to obtain a vectorized solution that should be faster than both existing remedies? Thank you.