Note that there are some explanatory texts on larger screens.

plurals
  1. POMATLAB: Performance problem with anonymous functions
    text
    copied!<p>Optimizing my MATLAB code, I stumbled upon a weird problem regarding anonymous functions.</p> <p>Like <a href="https://stackoverflow.com/questions/1673193/slow-performance-using-anonymous-functions-in-matlab-have-others-noticed-this">in this thread</a> I realized, that sometimes anonymous functions are running really slow. But with minimal changes to the function, it runs as fast as subfunctions or nested functions.</p> <p>I used this (simple) test file to reproduce the behaviour with Matlab R2010b under Windows 7 64-bit:</p> <pre><code>clear all; close all; clc; % functions fn1 = @(x) x^2; fn2 = @(x) double(x^2); % variables x = linspace(-100,100,100000); N = length(x); %% anonymous function y = zeros(1,N); t = tic; for i=1:N y(i) = fn1(x(i)); end tm.anonymous_1 = toc(t); %% anonymous function (modified) y = zeros(1,N); t = tic; for i=1:N y(i) = fn2(x(i)); end tm.anonymous_2 = toc(t); %% print tm </code></pre> <p>The results I got were:</p> <pre><code>tm = anonymous_1: 1.0605 anonymous_2: 0.1217 </code></pre> <p>As you can see the first approach is about 10 times slower. I have no idea what triggers this speedup/slowdown. I tried different things, getting nearly the same (fast) timings:</p> <pre><code>fn2 = @(x) 1 * x^2; fn2 = @(x) 0 + x^2; fn2 = @(x) abs(x^2); fn2 = @(x) x*x; </code></pre> <p><br/> Before I start profiling all of my functions, I would like to know if anyone has an explanation for this behaviour?</p> <p><br/> P.S.: I know that "vectorized" approaches are much faster, but in my case a solver will be evaluating the function for each variable time step, so that is not an option.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload