NoMan
NoMan

Reputation: 67

Why MATLAB is slow in this case compared to Mathematica

I have this code in Mathematica:

n = 5;
k1[x_, t_] := t^2;
k[m_, n_] := (1/(m!*n!)*D[k1[x, t], {t, n}, {x, m}]) /. {x -> 0, t -> 0};
kmn = Table[k[i, j], {i, 0, n}, {j, 0, n}];
kmn // MatrixForm

which get executed in just 0.03 seconds.

The following is the equivalent code I ended up in MATLAB:

syms t x;
n=5;
k1 = @(x,t) t^2;
kmn=zeros(n+1);
for i=0:n
    for j=0:n
        dift=subs(diff(k1,t,j),t,0);
        kmn(i+1,j+1)=(1/(factorial(j)*factorial(i)))*subs(diff(dift,x,i),x,0);
    end
end
kmn

But it executes in 4.970502 seconds.

What's wrong with my MATLAB code? Or, is this the fault of MATLAB? I want to reduce the processing time as much as possible.

Upvotes: 1

Views: 186

Answers (1)

horchler
horchler

Reputation: 18484

Trying to come up with "equivalent" code is always fraught with hazards. Mathematica and Matlab's symbolic math are quite different in their philosophies and implementations.

In the case of your proposed Matlab code, the first thing you want to try to do is remove the double for loop. Then try to vectorize and operations and reuse previous results. If possible, perform calculation numerically, rather than symbolically as long as you know the result will be exact (e.g., factorial for small integers). Here's an attempt to do some of these things:

syms t x;
n = 5;
k1 = @(x,t) t^2;
kmn = zeros(n+1);
j = 0:n;

dift = zeros(1,n+1,'sym');
for i = j
    dift(i+1) = subs(diff(k1,t,i),t,0);
end

fj = factorial(j);
for i = j
     kmn(i+1,:) = subs(diff(dift,x,i),x,0)./(fj.*fj(i+1));
end
kmn

The code could be further optimized to remove needless differentiation and substitution in the case when k1 isn't a function of x. And if k1 is a is meant to be a polynomial, there are many possibilities.

However, it'd be much better if we knew what underlying algorithm/equation you were trying to implement as there might be built-in functions that directly calculate some or all of the things you want.

Upvotes: 1

Related Questions