1

I have a matrix with symbolic variable in MATLAB like this:

syms x
f = [x^2 x^3 x^4];
save ('sym.mat','f')

Thus I saved the f matrix as sym.mat. Now I want to import this matrix into python. So I tried this:

import scipy.io as sio
matrix = sio.loadmat('sym.mat')
sym = matrix['f']

But it didn't work. I got this error, which is just a regular python keyerror.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'f'

However if f is not a symbolic matrix then this code works fine. Any ideas how I can deal with these matrices with symbolic variables?

2
  • What are the keys of matrix? Give us an idea of what loadmat returned. My guess is that MATLAB has saved a class and/or function that can't be translated into numpy structures. I seen problems in previous SO questions with MATLAB functions and dates. Commented Apr 8, 2018 at 4:38
  • I see from other posts that you already know about sympy. numpy and scipy don't have any symbolic functionality, so loadmat couldn't return the MATLAB equivalent even if it 'understood' syms. The best you can do is some how recreate them in sympy. Commented Apr 8, 2018 at 6:28

1 Answer 1

1

Scipy can't load MATLAB symbolic variables.

The best way to deal with your problem is to convert your Symbolic matrix into Matrix of chars(not matlab strings since it will cause errors too)

So here is what I mean:

In MATLAB, you can do something like that:

syms x
f = [x^2 x^3 x^4];
for i = 1:numel(f)
    if i == 1
        f2 = char(f(i));
    else
        f2 = [f2 ',' char(f(i))];

    end
end

save('sym.mat','f2')

This will display:

x^2,x^3,x^4

Now, In python you could do something like that:

import scipy.io as sio
path = 'H:\MatlabScripts'
matrix = sio.loadmat(path + '\sym.mat')
sym = matrix['f2'][0].split(',')
print(sym)

The result will be:

['x^2', 'x^3', 'x^4']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.