Matlab: Does calling the same mex function repeatedly from a loop incur too much overhead?

后端 未结 3 864
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 00:30

I have some Matlab code which needs to be speeded up. Through profiling, I\'ve identified a particular function as the culprit in slowing down the execution. This function i

3条回答
  •  余生分开走
    2021-01-18 01:30

    Well, this is the fastest I can make it in Matlab:

    %#eml
    function L = test(s,t)
    
        m = numel(s);
        n = numel(t);
    
        % trivial cases
        if m==0 && n==0
            L = 0; return; end
        if n==0
            L = m; return; end
        if m==0
            L = n; return; end
    
        % non-trivial cases
        M = zeros(m+1,n+1);    
        M(:,1) = 0:m;
    
        for j = 2:n+1
            for i = 2:m+1
                M(i,j) = min([
                    M(i-1,j) + 1
                    M(i,j-1) + 1
                    M(i-1,j-1) + (s(i-1)~=t(j-1));
                    ]);
            end
        end
    
        L = min(M(end,:));
    
    end
    

    Can you compile this and run some tests? (For some weird reason, compilation fails to work on my installation...) Perhaps change %#eml to %#codegen first, if you think that's easier.

    NOTE: for the C version, you should also interchange the for-loops, so that the loop over j is the inner one.

    Also, the row1 and row2 approach is a lot more memory efficient. If you're going to compile anyway, I'd use that approach.

提交回复
热议问题