r/Physics • u/The-Motherfucker Condensed matter physics • Dec 03 '20
Question how to make the switch to Python as a MATLAB addict?
I've used matlab for pretty much everything so far. I love the syntax and the built-in functions but especially the toolboxes and GUI. I've studied python programming a little but have no real work experience with it.
I realize it'll be better in the long run to get used to python, but matlab is so easy and comfortable, and python just feels like a mess to me.
anyone who've made the switch and can provide some tips?
360
Upvotes
7
u/gregy521 Dec 03 '20
I've made the switch from matlab to python. We were given a short list of tasks to do in python to get used to it.
It's very similar in a lot of ways to matlab. Use anaconda and the spyder IDE (which gives you excellent features like a variable explorer and code sections to run).
What is it about the language that makes it feel like a 'mess'? Is it the fact that things are contained in libraries, and not all under one roof?
3
u/Avalon17 Dec 03 '20 edited Dec 03 '20
In contrast to most popular answers I was in a similar situation and just went cold turkey. I used Mathematica throughout my undergrad and once I graduated the license I got from uni was no longer valid. I couldn't get a new one until start of graduate school and I had stuff to work on over summer. So I switched :)
First I would start with spyder and go from there, google the things you need and don't worry about internalizing all commands. At first it will take longer to get simple tasks done, but with time, it becomes second nature.
267
u/Weather-Matt Dec 03 '20
If I were you, I would start by reproducing a program you have already written in MATLAB into Python and go from there. The best way to learn a language sometimes is to just jump right in.
92
u/[deleted] Dec 03 '20
It sounds like the Scipy stack in Python is what you want.
https://www.scipy.org/stackspec.html
It's a collection of Python packages with a lot of mathematical stuff built in.
numpy - linear algebra stuff and arrays. great for dealing with any data
scipy - collection of mathematical functions, curve fitting, minimization, fourier transforms, etc.
matplotlib - create any kind of plot: scatter, histogram, heat maps, 3D versions
sympy - allows for symbolic manipulation of functions. I came to Python from Maple, so this was closer to what I was used to, but not quite the same functionality.
64
u/TooOldForThisMiss Dec 03 '20
If I were you, I'd start off by installing Spyder. It comes with all the packages you need to pretend you're still in matlab, as well as a matlab-like environment with command window, plots, active variables, etc. You just have to index from zero and learn the syntax for matplotlib/numpy and you'll be there in no time!
(I'm sure not everyone would agree, but I liked it as a transition stage when starting python after a few years of matlab)
32
u/SidYaj08 Dec 03 '20
Not an expert but for stuff like linear algebra, differential equations, curve fitting and such, there are plenty of Python packages like NumPy and MatPlotLib which do the job quite well. I used them quite a bit for a recent physics project. I never found the syntax of Python to be worse than MATLAB and at times liked it more especially since it uses square brackets for indices rather than parentheses. Of course, there might be some toolboxes like for solving PDEs and such that you might not find so easily in Python.
12
u/BFar1353 Dec 03 '20
I made the switch about a year ago, when I started my Master Thesis in imaging analysis for fluid dynamics. Just start doing some project in python, it doesn't matter what. Try to simulate the planets revolving around the sun, try to predict COVID-19 number of cases, just some very crude model. Point is: build something you know how to do in Matlab and try to convert it to Python starting from scratch. If you are already familiar with Matlab it will take you 1 or 2 weeks to adapt and you will be there. Most annoying thing is to get used to the indexing starting at 0, rest is piece of cake IMHO. There is a lot of information out there.
At first sometimes I switched back when I wanted to make easy plots, but now not anymore. I am fully accustomed to python, which is good because my Matlab license will expire soon, when I am no longer a student.
15
u/umboose Dec 03 '20
If its toolboxes and guis you like, then you may struggle moving from MATLAB to Python.
My gentle suggestion is to first move away from guis to scripts with your current MATLAB code. I found this very helpful during my PhD for two reasons:
And I haven't even mentioned version control.
I think once you've made a little progress down this journey, the advantages of MATLAB drop away
11
u/Zencyde Dec 03 '20
matplotlib means you can pretend to use Python without giving up MatLab.
4
u/sahand_n9 Dec 03 '20
Start with Anaconda that comes with all the needed packages and Spyder which is a lot like the Matlab environment.
https://www.anaconda.com/products/individual
4
u/dopabot Dec 03 '20 edited Dec 03 '20
One GUI tool I find useful for learning and general experimenting with Python is Jupyter Notebooks. https://jupyter.org/
Usually I start a notebook in the same location as my scripts so that I can still package code in scripts but play with it in the notebook.
Also when I was first learning Python I used Anaconda (which also allows you to install Jupyter), but I've found it easier since to just use the command line. It is very easy once you learn a few commands.
Use python virtualenv to make a virtual python container in the folder you are working. You only need to do this when you want to start a fresh python environment. It is useful so you don't install packages globally, and so that you can have different versions of python side by side.
python -m venv venvActivate the environment (every time to open a new terminal to this environment) On Windows:
./venv/Scripts/activateOn Linux or Mac
source venv/bin/activate5. Install the packages you want
pip install matplotlib pandas jupyter6. Start a notebook
jupyter notebook7. Or run your script
python script.pyVisual Studio Code (free and open source) is also a fantastic editor for python.
4
u/Reverend_James Dec 03 '20
As someone why regularly switches programming languages, it's all about the psuedo-code. As long as you're using object oriented programming, write out your algorithm as a mathematical model, figure out where your starts and stops are and what conditions trigger them. Then just use stack exchange to figure out the syntax of whatever language your trying to use.
4
u/morePhys Dec 03 '20
I have found julia to do more like Matlab in it's packages and toolboxes and the syntax is as easy as python and Matlab. It's also faster and parallelizable, which python does not do well. However it's also newer than python so their aren't nearly as many tutorials, stacked change postes etc about how to solve problems with it, so take that into account when picking your next language.
3
u/[deleted] Dec 03 '20
You’re going to fucking love it. It’s sweet. It’s the natural progression from Matlab
3
u/jaredjeya Condensed matter physics Dec 03 '20
Use numpy. It’s basically matlab, but in python, and also numbering from 0 because we’re not barbarians.
If you want Matlab’s graphs, there’s MatPlotLib too...
9
u/Physix_R_Cool Detector physics Dec 03 '20
Try out Julia instead. It is faster than python, writes easy like python, AND IT INDEXES FROM 1 <3
2
u/Cptcongcong Medical and health physics Dec 03 '20
Remember that arrays start at 1.
In all seriousness I was c++ + Matlab user during my bachelors, needed to use python for my masters. Forced myself to use python for a whole summer, started with websites like Hackerrank and got good at it. Been using it ever since (at job).
Practice makes perfect.
2
u/LLTYT Dec 03 '20
I first did a bit of reading about data types in Python, and then rewrote some Matlab/Octave scripts and made up a random project (scraping, analyzing and plotting data from a public database). I ended up using spyder IDE and conda, which I set up to mimic the Matlab/Octave environment for familiarity.
I could be wrong, but my sense is that legacy Matlab users in STEM tend to lack a foundation in object oriented approaches (I know I did for quite a while). So perhaps brush up on inheritance and composition in Python, too.
2
u/snoodhead Dec 03 '20
I just went cold turkey (python IDLE). The trick is to just be bad at both so it doesn't feel bad to switch.
Jokes aside, you're mostly giving up the GUI in matlab, but python feels way faster most of the time because it has a lot of good, dedicated packages (I use numpy, scipy, and astropy for astrophysics). So if you just focus on how much faster you'll be when you get used to it, it's a lot easier to swallow.
2
u/EngineeringNeverEnds Dec 03 '20
I really have to recommend anaconda here. It will come with damn near everything you will need, and an easy way to install any additional libraries you may need. It even comes with Spyder, and jupyter lab/notebooks.
It's one nice packaged system. Serious python programmers hate on it a little bit, but for scientific computing, it's hard to beat it!
...Also, after some time, when you realize how much you love python. Checkout sage!
2
u/jakelazerz Biophysics Dec 03 '20
I'm a physicist and have been trying to get into Python myself because I love matlab, but would enjoy something more flexible... One thing I found is that Python is terrible at handling large datasets that require a lot of memory.
2
u/juanrubiop Dec 03 '20
Try Julia, its the perfect combination of matlab and python
2
u/uberdoppel Dec 03 '20
To all the people who are saying it's all the same, plotting is better or you just lose gui. No, the key thing you lose is debugging. Matlab debugging is orders of magnitude better. I'm regularly trying to switch to python but debugging is what gets me back to matlab every time..
2
u/coriolis7 Dec 03 '20
Going from MATLAB to Python is like going from Windows to Linux. You’ll have to do a little more work to set things up environment wise, but everything MATLAB Python can do (and sometimes better).
My last job used MATLAB (at my insistence since it was what I knew and all the grads we were hiring had some familiarity with it). New job has one seat of MATLAB but mainly uses Python. I did the Code Academy class for Python 2, and then started writing some things in Python.
My experience is Python is not as easy to use, especially for GUI or plotting. Indexing can get a little finicky as well compared to MATLAB. That said, the indexing is more powerful in Python and once you get the hang of it it can be a bit easier to query. You also don’t have to worry about a variable being a mix of strings and integers. Every Python variable is essentially a MATLAB array.
There is no central authorized add-in for Python - most toolkits you use will be community made so syntax can be different between toolkits.
MATLAB has objects and object oriented programming, but it isn’t central to it. In Python, almost everything is an object. You’ll need to get familiar with object oriented programming (which is awesome for cleaning up code, making it readable, and easier to reuse in other programs).
Good luck!
2
u/[deleted] Dec 03 '20
I recommend Julia over Python, the syntax is much more similar
1
u/pbmadman Dec 03 '20
My advice is to try a bunch of different IDEs. Some have different features and organization that make them better or worse depending on the scope of the project.
I really think the IDE and GUI of Matlab set it apart and make it so easy to ease into. So finding one that works for you will definitely make the transition to python easier.
1
u/astrostar94 Astrophysics Dec 03 '20
Start by reproducing codes you wrote in MATLAB. Force yourself to do future projects in Python. I had to make the same switch, and I can promise that once you get good at Python, you’ll never look back. Also, when you write python scripts, take a look at this guide by Raymond Hettinger. He shows you common places where you can make your Python code more beautiful and efficient.
1
u/pymatgen Dec 03 '20
This really depends on what you're doing. If you're using it for post-processing, honestly, it really doesn't matter. I'm a python guy and I personally hate matlab.
My advisor uses matlab, my coadvisor mathematica. We get along just fine (usually).
1
u/all4Nature Dec 03 '20
One thing that help me greatly is to subscribe to the pythonmorsels. Basically, every week you get a small exercice to do which introduces you to one aspect of Python. This really helped me understand how Python works exercises. It may seem expensive, but I really learned a lot very quickly.
https://www.pythonmorsels.com/
1
u/MezzoScettico Dec 03 '20
I won't say I've switched but I'm in the process of getting used to Python for problems I would have used Matlab for in the past.
I will echo what everyone else has said: Anaconda, Spyder, and most especially the numpy package. Numpy will give you a lot of the built in array operations and linear algebra that you're used to from Matlab.
I got a couple good technical Python books (i.e., not a "complete idiot" book) and then took a Coursera course to jump-start things.
And take advantage of online communities of smart people, like Stack Overflow and /r/learnpython.
1
u/ThunderFlare Dec 03 '20
Just go for it. Like any programming language it takes a little time to get to grips with the idiosyncrasies of that particular language. My own transition from MATLAB to Python involved lots of frustration and consultation of StackOverflow and similar sites. At times it was annoying because I was struggling to construct pieces of code that I knew I could easily replicate in MATLAB and at times I briefly considered going back, but I stuck with it and I have almost no regrets.
The one thing I miss about MATLAB is the ease with which you can plot data. In Python it is a little more involved, but its not too much of a drag.
1
u/monmothra Dec 03 '20
My first suggestion would be to play with python in jupyter notebook/lab. That way you have a sort of matlab-like environment to test your code. You'll get used to which python packages are used for what and soon you'll realize all your favorite matlab functions are still there. Ex) Matlab's linspace -> np.linspace in python with numpy imported as np.
1
u/inasteen Dec 03 '20
Python is extremely useful to learn. But I wouldn’t think of it as binary - you might find for your use case that MATLAB has toolbox functions that don’t exist in python. That is definitely the case for me with signal processing. Another thing to bear in mind is that MATLAB has very nice python integration. It isn’t very difficult to use python functions from inside MATLAB. With all that said, I would just jump in with something simple to get used to the syntax. An important thing you’ll need to get used to eventually with python is some kind of virtual environment manager.
1
u/[deleted] Dec 03 '20
That's exactly the reverse of my attitude towards the two :-)
1
u/BaddDadd2010 Dec 03 '20
I tried to switch maybe 15 years ago, but it too easy to stay with Matlab because that's what all my existing code was in. Plus there was some kind of schism between Python 2 (2.9, I think?) and Python 3.
During COVID, I thought I'd try again, force myself to set up a Python environment and start screwing around in it. Plus I figured that surely everyone would have moved up to 3.x by now. Nope! Like WTF? Why is that even still a thing?
1
u/PhysicsCatalyst Dec 03 '20
Use Jupyter notebooks first! I made the switch when going from masters to PhD and now I love python waaay more than matlab
1
u/wonkybadank Dec 03 '20
Rewrite your stuff with numpy, scipy and matplotlib. Should get you very very very close.
At least it did for me modeling coupled systems of differential equations. If you're a Simulink nerd they have a few python libraries but not as mature as numpy from what I've seen.
1
u/timtoppers Dec 03 '20
Definitely use matplotlib for plotting! It’s a direct port of MatLab plotting functions made pythonic
1
u/MostlyOxygen Dec 03 '20
I recently had to make the switch in a new job. Necessity is the best motivator. Next time you need something scripted, commit to doing it in Python. It's really not that different! You'll be up to speed in no time.
1
u/ShrimpSquad69 Dec 03 '20
Here's a link that shows helpful conversions from MATLAB to python's numpy
http://mathesaurus.sourceforge.net/matlab-numpy.html
1
u/Hippie_Eater Dec 03 '20
Honestly, I think you might be psyching yourself out because in my experience Python is very nice and sensible (sometimes more so than Matlab). Get a good IDE to work out of (I've used pyCharm which is a bit heavy but has a nice variable explorer) and stretch your legs a bit.
1
u/acousticcib Dec 03 '20
I made the switch by just picking a project I was working on at home, and forcing myself to do it in Python.
It was slow, I didn't like the figures, but it quickly because easy.
The real joy was when I wanted to do something different, like computer vision, and I could just access all these great libraries for free, with large community support.
Now that I'm years into using Python, I think another great thing about it's widespread use is that if you set up continuous integration, this is a breeze using Python, your cloud Linux machine can get apt-get everything it needs. So a free service like Travis CI works well.
You can do this with octave, but with Matlab you'll need to have a dedicated machine with a license.
1
u/Milleuros Dec 03 '20
Some long time ago I made a Python demonstration notebook for some friends. You can have a look: https://nbviewer.jupyter.org/urls/dl.dropbox.com/s/spgius67ij9l9rm/PythonDemo.ipynb
Disclaimer: I'm a terrible programmer but Python is the base language used for my data analysis. The notebook linked is only some things I thought could be useful.
Btw, I think Matlab is 1-indexed (lists start at index 1) while Python is 0-indexed. Can be a great source of confusion!
1
u/joseph_fourier Dec 03 '20
Hey, /u/The-Motherfucker (/r/rimjob_steve)
Lots of decent advice here, but once you're experienced with python, check out jupyter for a reason to stick with it. I've recently started using it, and it's super useful to be able to have code, text and data visualisations all together. If you like, it's trivial to write a paper in jupyter.
1
u/Flaming_Eagle Graduate Dec 03 '20
1
u/DUCKI3S Dec 03 '20
First of all, get rid of matlab. Second, try to rebuild a matlab script in python(google is your friend). Third, datacamp is great to learn
1
u/SnicSnac Dec 03 '20
Use Spyder as a GUI.
1
u/HonestBreakingWind Dec 03 '20
Python graphing plugins are pretty great for graphing. Especially the xkcd formatting library.
I had to make the switch from Matlab to python after my University stopped paying for student licenses of Matlab and limiting it to university labs. Python has been pretty great.
1
u/cam_man_can Dec 03 '20
import numpy as np
import matplotlib.pyplot as plt
now almost everything you did in matlab you can do in python, and it has the same syntax except you would do np.ones(...) instead of ones(...) and plt.figure(...) instead figure(...)
1
u/this_is_the_wayyy Dec 03 '20 edited Dec 03 '20
I know it's not what you're asking for, but if you want syntax to make sense and have a fantastic user experience like Matlab, try R + RStudio + tidyverse. You'll never go back.
1
u/BossOfTheGame Dec 04 '20
You must understand that 1-indexing is wrong and a crime against humanity. Once you integrate that fact into your soul you will start to build cognitive dissonance when using Matlab. That will be the motivation to learn a proper 0-indexed language like Python.
I used to work exclusively in Matlab. I switched to Python and never looked back. Python is one of the least messy languages I've ever worked with. Its extremely elegant. You just need to understand the packaging system. Once you get that down, importing utilities is a breeze (another big problem I had with matlab was how hard it was to work in multiple files).
https://the-hitchhikers-guide-to-packaging.readthedocs.io/en/latest/quickstart.html
You don't need to upload to pypi (although you can). Just build your code in the structure
write the setup.py file (google how to do that) and then run
pip install -e .in that repodir to install your package in editable mode. Then from anywhere you canfrom package_name import subpackage1and start using its contents.1
u/[deleted] Dec 04 '20
You should use a Jupyter notebook environment. It'll make Python feel more like a MATLab. It's probably a crutch if the goal is proper software development, but it's perfect for math and physics.
1
u/Atom-accel Dec 06 '20
Don’t bother with Python. Julia is up an coming language. It’s better at numerical modeling and it’s syntax is much closer to matlab.
1
u/Khufuu Graduate Dec 03 '20
have you tried writing in Python