How to convert the MATLAB code into the Python?

Hello, I have a matlab code for the quantitative differential phase contrast imaging and the code is very big and complicated as well. But the problem is the institute where I am working does not allow to use matlab and they have python and LabVIEW, so I would like to convert the matlab code to python or someone knows how to run the matlab code in python then it also be very helpful.
I have attached the main code.
Thank you.

9 Kommentare

Kevin Chng
Kevin Chng am 26 Okt. 2018
Why don't compile it into python package? Then you can call it in your python.
If don't have compiler, you can use MATLAB api for python.
Therefore, you no need to re-write those big and complicated code in python.
Yes , this can be a one solution, but I do not have python package in matlab.
or
but I have octave so can I run the .m file into the octave ?(the code) I have attached.
Kevin Chng
Kevin Chng am 1 Nov. 2018
Hi, Take a look at this (API for Python)
or
do you have matlab compiler? It is the most easier solution.
Actually the institute where I am working is not allowing me to you the matlab at all, so if you have compiler then could you convert the matlab code into python for me?
I have attached the matlab codes.
Deepu S S
Deepu S S am 5 Jan. 2022
To convert Matlab to python, a tool named SMOP (Small Matlab and Octave to Python Compiler) is used. This tool is capable of understanding basic Matlab code and then parsing it to python. Although there are always limitations to every tool, this tool works best for small-level codes.
@Deepu S S have you ever try SMOP ? if yes, i need help.😊
Gurram
Gurram am 13 Sep. 2022
@Milind dilipkumar Patel Even my problem is also similar to your's
could pls tell me have you got the solution ?
Suma K
Suma K am 16 Dez. 2023
can u tell how to convert matlab simulink to python programm
Puma
Puma am 16 Apr. 2024
c=math.copysign(y, z) covertir a matalb

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 14 Nov. 2024

0 Stimmen

MATLAB provides two-way integration with many programming languages, including Python. The MATLAB Engine API for Python allows you to call MATLAB functions from Python. Similarly, if you have functions and objects in Python, you can call them directly from MATLAB using the Python Interface. Finally, you can build Python packages from MATLAB programs by using MATLAB Compiler SDK™. These packages can be integrated with Python applications and can be shared with desktop users or deployed to web and enterprise systems. To learn more about using MATLAB with Python go here.

Weitere Antworten (4)

madhan ravi
madhan ravi am 26 Okt. 2018
Bearbeitet: madhan ravi am 26 Okt. 2018

4 Stimmen

You can use numpy framework which contains matlab libraries.
See cheat sheet , I faced similar situation as you but raged with the cheat sheet, good luck!
MathWorks Support Team
MathWorks Support Team am 25 Okt. 2022

1 Stimme

MATLAB provides two-way integration with many programming languages, including Python. The MATLAB Engine API for Python allows you to call MATLAB functions from Python. Similarly, if you have functions and objects in Python, you can call them directly from MATLAB using the Python Interface. Finally, you can build Python packages from MATLAB programs by using MATLAB Compiler SDK™. These packages can be integrated with Python applications and can be shared with desktop users or deployed to web and enterprise systems. To learn more about using MATLAB with Python go here.

4 Kommentare

This Answer does not address the issue that "But the problem is the institute where I am working does not allow to use matlab". Calling MATLAB from Python is not an acceptable solution for places that do not permit MATLAB.
Daniel
Daniel am 17 Sep. 2023
@Walter Roberson - I don't think it's fair to call the prohibition of Matlab an issue, but rather a feature :)
Nonetheless, while I've only spent a few moments now installing and trying out the various solutions to convert Matlab to Python code, the first one so far that has worked out-of-the-box so far on some old projects from school was: https://www.codeconvert.ai/matlab-to-python-converter. I'm not sure what the underlying model is that is used to convert.
ChatGPT's conversion was the best, even pulling some common plotting code out into a plotting function which didn't exist in my original script. I highly recommend giving ChatGPT a look for folks looking to migrate their code away from Matlab.
The original poster of the question used the term "problem", rather than a phrasing such as "great thing", so it was not a "feature" to the original poster.
Daniel
Daniel am 17 Sep. 2023
@Walter Roberson - ChatGPT may be useful to help you understand sarcasm as well :)

Melden Sie sich an, um zu kommentieren.

Gurubasava Bhure
Gurubasava Bhure am 24 Jul. 2021
Bearbeitet: Walter Roberson am 26 Okt. 2022

0 Stimmen

clc()
clear(mstring('all'))
close(mstring('all'))
# Generating the bit pattern with each bit 20 samples long
b = round(rand(1, 30))
pattern = mcat([])
for k in mslice[1:30]:
if b(1, k) == 0:
sig = -ones(1, 20)
else:
sig = ones(1, 20)
end
pattern = mcat([pattern, sig])
end
subplot(4, 1, 1)
plot(pattern)
axis(mcat([-1, 600 - 1.5, 1.5]))
title(mstring('Original Bit Sequence'))
# Generating the pseudo random bit pattern for spreading
d = round(rand(1, 120))
pn_seq = mcat([])
carrier = mcat([])
t = mcat([mslice[0:2 * pi / 4:2 * pi]])# Creating 5 samples for one cosine
for k in mslice[1:120]:
if d(1, k) == 0:
sig = -ones(1, 5)
else:
sig = ones(1, 5)
end
c = cos(t)
carrier = mcat([carrier, c])
pn_seq = mcat([pn_seq, sig])
end
# Spreading of sequence
spreaded_sig = pattern *elmul* pn_seq
subplot(4, 1, 2)
plot(spreaded_sig)
axis(mcat([-1, 600 - 1.5, 1.5]))
title(mstring('Spreaded signal'))
# BPSK Modulation of the spreaded signal
bpsk_sig = spreaded_sig *elmul* carrier# Modulating the signal
subplot(4, 1, 3)
plot(bpsk_sig)
axis(mcat([-1, 600 - 1.5, 1.5]))
title(mstring('BPSK Modulated Signal'))
#Plotting the FFT of DSSS signal
y = abs(fft(xcorr(bpsk_sig)))
subplot(4, 1, 4)
plot(y / max(y))
xlabel(mstring('Frequency'))
ylabel(mstring('PSD'))
#Demodulation and Despreading of Received Signal
figure()
rxsig = bpsk_sig *elmul* carrier
demod_sig = mcat([])
for i in mslice[1:600]:
if rxsig(i) >= 0:
rxs = 1
else:
rxs = -1
end
demod_sig = mcat([demod_sig, rxs])
end
subplot(3, 1, 1)
plot(demod_sig)
axis(mcat([-1, 600 - 1.5, 1.5]))
title(mstring('Demodulated Signal'))
despread_sig = demod_sig *elmul* pn_seq
subplot(3, 1, 2)
plot(despread_sig)
axis(mcat([-1, 600 - 1.5, 1.5]))
title(mstring('Despreaded data'))
#Power Spectrum of Despreaded data
z = 0.5 + 0.5 * despread_sig
y = abs(fft(xcorr(z)))
subplot(3, 1, 3)
plot(y / max(y))
axis(mcat([0, 500, 0, 1.5]))
xlabel(mstring('Frequency'))
ylabel(mstring('PSD'))

17 Kommentare

Deepu S S
Deepu S S am 5 Jan. 2022
Python is one of the easiest high-level programming languages ever created which is as easy as reading and writing English. It was first released in the 1990s by Guido van Rossum and now is been contributed by hundreds of developers worldwide.
Whereas, Matlab is closed source software managed by Mathworks. And most importantly, Python is free, unlike Matlab.
We can get thousands of modules within Python that can be helped to access any kind of API you need in your project. Moreover, you can edit the original source code of modules in Python.
Whereas, in Matlab, this is next to impossible. Also, the support for python by developers all around the world is increasing at an exponential rate.
According to StatisticsTimes, python is the most searched language in the PYPL index1. Also, considering the usage efficiency and support available, it’s already concluded that Python is way more flexible than Matlab.
Matlab is used by many students for their thesis projects and many other tasks. Especially in the field of computing and mathematics, Matlab is considered to be a prominent programming language among all. Moreover, as it supports Object-Oriented Programming and Data Visualization codes, you can easily use it to your advantage. But as the world changes, new programming languages come into the picture. To convert Matlab to python, we have two options, either do it manually or take the help of some tool.
To convert Matlab to python, a tool named SMOP (Small Matlab and Octave to Python Compiler) is used. This tool is capable of understanding basic Matlab code and then parsing it to python. Although there are always limitations to every tool, this tool works best for small-level codes.
In this post, we’ll go through all the available ways to convert Matlab code into python code without any difficulty.
Deepu S S
Deepu S S am 5 Jan. 2022
https://www.pharmacoengineering.com/2018/11/29/converting-matlab-code-to-python refer this article it will deffinetly help u.Goodluck.
"And most importantly, Python is free, unlike Matlab."
Really? That is what is most important?? That it is free?
There is a certain comic strip that has been running for decades, which has been widely syndicated, and which can be read for free. Does it follow that the most important thing about that comic strip is that it is free? More important than the fact that the comic strip is fundamentally boring and repetitive, that none of the main characters ever does anything admirable (or, rather, only does admirable activities to try to impress someone who has made it clear that they do not like the character and do not want a relationship with them)?
yes, the most import thing about python is that it is free. No individual can afford Matlab.
There is a completely-free programming language for which an x86-based compiler has been built that is less than 275 bytes long. You could print out the entire compiler for it on a small sheet of paper, and take the paper with you if you have to, instead of having to download anything. There are only 8 commands in the programming language, so there isn't much to teach.
Free, extremely small compiler, only a small number of commands. This would clearly be better than Python according to any objective measure, right ?
And yet... the programming language is only used by a very very small number of people in the world. Because being free (or small) is not the most important thing about a computer language.
"No individual can afford Matlab."
Is the question about whether MATLAB is affordable or is the question about whether MATLAB is free ? Because those are very different things.
I met with some people once who absolutely refused to consider using MATLAB for any part of a project. They had access to cheap MATLAB licenses, but it was out of the question for them to use MATLAB for anything. Because MATLAB wasn't Open Source. They preferred to spend over a year writing Open Source code to implement functionality that could have been done somewhat easily in MATLAB. The cost of the MATLAB licenses would have been a small fraction of the cost of their salaries for the time spent writing equivalent code.
Is the initial cost of MATLAB ever a problem? Yes, sometimes it is.
I sometimes have to skip potential consulting work because I do not have the commercial license for the toolbox(es) that would be needed. In a business, toolbox price can be amoratized over the expected usage -- but unless the contract is fairly large, clients are probably going to oppose paying a "supplies" fee to cover several thousands extra in license costs. Though if it cuts a couple of months off of the development schedule (time saved not having to develop and test replacement facilities) then they might be willing. Sometimes you can't afford not to use a well-developed and tested software base with a technical support contract.
Samuel Gray
Samuel Gray am 2 Mai 2022
Bearbeitet: Samuel Gray am 2 Mai 2022
...if I worked for Matlab, I wouldn't touch this question with a 10-foot pole.
The fact that you're even entertaining it validates it while undermining Matlab's entire pricing schedule.
I am not sure who you are referring to? I am the most recent person to have replied, but I do not work for Mathworks.
Samuel Gray
Samuel Gray am 3 Mai 2022
Bearbeitet: Samuel Gray am 3 Mai 2022
well that's fair enough, I suppose this is a running concern, how to identify exactly who participates in this forum who IS a Mathworks employee...funny how this came up just yesterday in another thread...
@Samuel Gray the staff are marked with a badge "STAFF"
...ah, that makes sense.
I did not know that.
Well, still. My comment isn't dramatically changed if you aren't a Mathworks employee, and I will see about finding out how to "reply" as opposed to just "add to thread".
Honestly not like I use this forum often, just when I need to.
The forum supports @ references. Type an @ and that brings up a menu that allows you to tag a person; you might need to type more of their name to get into the sub-menu on-screen.
...see?
So it's like other forums in that way, especially like YT forums, but there's no obvious indication of that...
But if you've spent most of your formative years posting on forums that support @ replies, you'd just do that by rote and find that it works. I did find it by typing in @ (for another reason) and as you see if you try that, all sorts of user names will pop up.
So it's dangerous to assume that something is or is not a certain way because quite often it's just a matter of your background and your willingness to experiment and do some research on Google. Some people like that about Life and some don't.
When you are in the editor here, the right hand side has a circled question mark with notation HELP . If you click on that you get documentation about the editor, including
When you type @, a popup displays the community members already in the Q/A thread. As you keep typing, the list expands to include members not in the thread. A mentioned community member receives a notification when the question/answer/comment is posted. Each mention links the post to the community member's user profile.
Jim
Jim am 7 Mär. 2025
Gurubasava Bhure : In reference to the code posted: I did open in onliine Matlab. All kinds of errors occurred.
The pound symbol, used for comments in python, is not used for comments in Matlab. A host of other erros occurred. I dumped the effort.
This post is about the conversion of Matlab code to Python code. Not much there in this post.
I believe the posted (python) code is intended to be the python translation of the MATLAB code originally asked about.
Jim
Jim am 7 Mär. 2025

Has anyone tried the code? Subplot is used, implying a matplotlib import, but no declaration is evident.

The option to open in online matlab is misleading, especially when the code, in that app, is credited with multiple errors.

No '#!/bin/python' header.

But... I get the idea.

The use of mstring (mutable strings) in contests where fixed strings make more sense, suggests to me that some facility such as chatGPT was used to convert the code.

Melden Sie sich an, um zu kommentieren.

Arash Rabbani
Arash Rabbani am 26 Mai 2022

0 Stimmen

You may want to check these tutorials on how to convert a code from MATLAB to python.

Kategorien

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by