0

Suppose I have a function

enter image description here

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.

yurnero
  • 315
  • 2
  • 9
  • 2
    Just replace all `*` with `.*` (element-wise product)` and all `^` with `.^` (element-wise power) – Suever Jun 25 '16 at 22:28
  • @Suever Amazing! It's working for this toy example. Lemme try it on my real problem. Thank you so much. – yurnero Jun 25 '16 at 22:30
  • Just keep in mind that all dot operations (`.*`) are element-wise. If something works for scalars and you just want to do that for all corresponding elements, just with the element-wise option for all relevant operators. – Suever Jun 25 '16 at 22:31
  • @Suever I know about the dot thing but I was shaky in using it. I tried just now with the real code and the run time is reduced 4-fold. Thank you very much. If you don't mind, perhaps you can make a short answer, and I will accept to close this question. – yurnero Jun 25 '16 at 22:38
  • 3
    You could replace `meshrgrid, ndgrid` codes with `bsxfun` for further performance boost. See few examples : [1](http://stackoverflow.com/a/25162350/3293881) [2](http://stackoverflow.com/a/25885889/3293881) [3](http://stackoverflow.com/a/27341488/3293881). – Divakar Jun 25 '16 at 22:44
  • 1
    It's not worth an answer. You can leave it here but I'm going to mark as a duplicate since it's been answered many times before. – Suever Jun 25 '16 at 22:44
  • @Divakar That is ridiculous, another 4 fold reduction in computation time. Salute to you my man. – yurnero Jun 25 '16 at 23:03
  • Salute `bsxfun` instead! ;) – Divakar Jun 25 '16 at 23:04

0 Answers0