Table of Contents

Convert MATLAB to Python with Google Gemini CLI in Engineering Education

|8 mins read
aigeminigoogle gemini climatlabpythonmatlab to pythonai code migrationautomated code conversioncode translationengineering educationuniversityteachingclicode-conversionprogramming

How to automatically convert your Matlab Code to Python with AI

As someone who teaches programming for mechanical engineering students at Ravensburg Weingarten University, I've always been wondering about AI's ability to handle complex, real-world code conversion tasks. Sure, it's great for simple scripts and basic examples, but what about a full-fledged object-oriented system built over an entire semester? My initial skepticism was completely shattered when I tried Google's Gemini CLI on one of my challenging teaching projects.

What started as a potentially weeks-long manual conversion project turned into a 25-minute coffee break. Here's my story of how Gemini CLI completely blew me away.

The Challenge: Rewrite the full Matlab Codebase in Python

Let me set the scene. At our university, I teach a two-semester programming class for mechanical engineering students. The first semester introduces students to IT fundamentals using MATLAB - variables, loops, functions, the usual suspects.

In the second semester, we dive deep into object-oriented programming using MATLAB, and we do it through a comprehensive car simulation project. Students build a complex system with multiple interconnected classes (here only a selection is shown to get a better picture):

  • Motor class: Handles engine specifications, torque curves, and efficiency maps
  • Drive class: Manages transmission, gear ratios, and power delivery
  • Car class: Integrates all components and handles vehicle dynamics
  • Cycle classes: Implements standardized driving cycles like NEDC, WLTP
  • Specification classes: Manages vehicle parameters from Excel configuration files

By the end of the semester, students have built a fully functional car simulator that can:

  • Load vehicle specifications from Excel files
  • Simulate driving cycles with realistic physics
  • Calculate fuel consumption and emissions
  • Generate performance metrics like acceleration and top speed
  • Export detailed analysis data for further study
  • Extensive Plotting

It's a substantial codebase for a 2nd semester student - typically 500-700 lines of object-oriented MATLAB code that represents weeks of student work.

The Problem: License Costs and Future-Proofing

Why are we even considering this task? Here's where reality hits. MATLAB licenses are expensive - really expensive. For a university, we're talking about thousands of euros per year for student licenses. And there's always the looming question: what happens if the university decides to cut ties with MathWorks? This is not far-fetched considering the tremendous efforts to cut costs.

Additionally, I wanted to adapt this excellent curriculum for another course that focuses more on general programming principles rather than engineering-specific tools. Python seemed like the natural choice - it's free, widely adopted in industry, and has excellent libraries for numerical computing and data analysis. To me, it is superior as an introductory language to programming for mechanical engineering students.

But here's the thing: manually converting the complete MATLAB code to Python? That's at least a weekend project that would require:

  • Researching Python equivalents for MATLAB-specific functions
  • Rewriting the object-oriented structure to follow Python conventions
  • Testing and debugging the converted code extensively
  • Ensuring all Excel integration still works properly

I was mentally preparing for 1-2 days of tedious work. Then I remembered Google's Gemini CLI that I'd been meaning to try out.

Enter Gemini CLI: I cannot believe this Tool is free

Google's Gemini CLI is a command-line interface that gives you access to Google's powerful Gemini AI models. Unlike web interfaces, the CLI allows you to work with local files, handle large codebases, and integrate AI capabilities directly into your development workflow.

I'll be honest - I did expect to get Python code back which would not do what it was supposed to do and I would have to debug my way through. Usually, they'd handle simple functions okay but completely butcher anything with complex object relationships or domain-specific logic. Sometimes I had the experience of reaching a point where I could have implemented it by myself faster as I was iterating and cursing at the cursor for not doing what I had in mind.

Setting Up Gemini CLI

Getting started with Gemini CLI is straightforward. You need to follow the instructions on their GitHub Repository

The setup process is well-documented, and getting API access is free for very generous usage levels (as of 07/2024) - perfect for academic use.

The Conversion Process: Surprisingly Simple

Here's where it gets interesting. Instead of trying to convert everything at once, I decided to take a methodical approach. I started with a simple prompt that included the entire MATLAB codebase. I provided the full semester's PDF as documentation, too. The code is quite well documented (over 70 pages), broken up into different tasks (where only the last task is concerning the codebase for this exercise)

"

Convert this MATLAB object-oriented car simulation to Python. Preserve the class structure, maintain Excel integration, and ensure all methods work identically to the original. Focus on clean, Pythonic code while keeping the same functionality. In question, look for definitions in the provided documents. Feel free to ask if you need to clarify your tasks or certain implementation details. Use uv as a package manager, numpy and matplotlib for plotting.

Gemini Prompt

What happened next blew my mind. As I said, I didn't expect too much, so I didn't pay attention. Within the next half hour, I went and sat outside, casually checking back if any requests had to be approved. When I came back after that half hour, Gemini had produced a complete Python implementation that included:

  • Proper Python class structure with appropriate inheritance
  • Excel integration using pandas and openpyxl
  • NumPy arrays replacing MATLAB matrices
  • Matplotlib plotting for all visualization needs
  • Type hints for better code documentation
  • Error handling that was actually better than the original

But here's the kicker - it wasn't just a mechanical translation. Gemini had made intelligent decisions about Python best practices. For example, it converted MATLAB's cell arrays to appropriate Python data structures, replaced MATLAB's `xlsread` with pandas' more robust Excel handling, and even added proper docstrings to all methods.

Testing: The Moment of Truth

Okay, so I had Python code that looked good on paper. But the real test would be running it against our standard test scenario. I loaded up the same Excel configuration files we use in class and ran a NEDC cycle simulation.

The results were... identical. Not just close - identical. The Python version was producing exactly the same fuel consumption figures, acceleration curves, and efficiency metrics as the MATLAB original. Even the legends on the plots were the same. It even kept the German language for the plots as it was the case in the reference material.

Everything worked perfectly. I was prepared to spend hours debugging, but there was literally nothing to debug. The code just... worked.

A matplotlib plot consisting of 4 graphs which show the output of the Python implementation for the car modelling

What Made This Conversion So Successful?

Reflecting on why this worked so well, I think several factors contributed to the success:

1. Well-Structured Original Code

The MATLAB code was well-organized with clear class hierarchies, proper encapsulation, and good documentation. This gave Gemini a solid foundation to work from.

2. Clear Context in the Prompt

I didn't just ask for a conversion - I provided context about what the code does, what the expected behavior should be, and what Python conventions to follow.

3. Gemini's Understanding of Both Languages

Gemini clearly has deep knowledge of both MATLAB and Python idioms. It didn't just translate syntax - it understood the semantic meaning and chose appropriate Python equivalents.

4. The Right Level of Complexity

This wasn't a trivial toy example, but it also wasn't a million-line enterprise system. It was the sweet spot where AI really shines - complex enough to be challenging for humans, but structured enough for AI to understand.

5. An extensive Documentation as a PDF

One big factor was also the PDF which I attached to the prompt. I am sure this was used via RAG and as the code was documented in detail, it served for Gemini to understand what each class was doing and what formulas were used and why.

Practical Implications for Education

This experience has profound implications for how we approach curriculum development and tool selection in education:

License Independence

We're no longer locked into expensive proprietary tools. If licensing becomes an issue, we can migrate our entire curriculum to open-source alternatives without starting from scratch. And the effort to do so is very reasonable.

Multi-Language Teaching

The same conceptual framework can now be taught in multiple programming languages. Students can learn the principles in MATLAB and see the same concepts in Python, reinforcing the universality of programming concepts.

Rapid Prototyping

New teaching examples and exercises can be quickly adapted between languages, allowing for more diverse and flexible curriculum development.

The Future of Programming Education

This experience makes me optimistic about the future of programming education. AI tools like Gemini CLI don't replace the need for understanding programming concepts - they amplify our ability to teach those concepts effectively.

Students still need to understand object-oriented design, algorithmic thinking, and problem-solving. But now we can focus on these fundamentals without being constrained by the specifics of any particular language or tool.

We can teach the same car simulation project in MATLAB for engineering students who need to understand the mathematical foundations, and in Python for computer science students who need to understand general programming principles. The concepts remain the same; only the syntax changes.

Final Thoughts

Twenty-five minutes. That's all it took to convert a semester's worth of complex, object-oriented MATLAB code to perfectly functional Python. No debugging, no manual corrections, no late nights trying to figure out why the fuel consumption calculations were off by 0.1% or how to get that special plot style in matplotlib.

If you're an educator dealing with legacy code, considering a language migration, or just curious about what modern AI can do, I highly recommend giving Gemini CLI a try. You might be as surprised as I was by just how capable it has become.