Executing MATLAB Scripts in Python - 12.3 | 12. Integrating SciLab/MATLAB with Python for Scientific Computing | IT Workshop (Sci Lab/MATLAB)
Students

Academic Programs

AI-powered learning for grades 8-12, aligned with major curricula

Professional

Professional Courses

Industry-relevant training in Business, Technology, and Design

Games

Interactive Games

Fun games to boost memory, math, typing, and English skills

Executing MATLAB Scripts in Python

12.3 - Executing MATLAB Scripts in Python

Enroll to start learning

You’ve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.

Practice

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to MATLAB Scripts in Python

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Today, we’re going to explore how to execute MATLAB scripts using Python. Can anyone tell me what a .m file is?

Student 1
Student 1

Isn’t it a script written in MATLAB?

Teacher
Teacher Instructor

Exactly! .m files are MATLAB script files. In Python, we can run these scripts using the MATLAB Engine API. So, how do we start this API in Python?

Student 2
Student 2

We need to import `matlab.engine`?

Teacher
Teacher Instructor

Right! After that, we initiate the MATLAB engine with `eng = matlab.engine.start_matlab()`. This allows us to communicate with the MATLAB session.

Student 3
Student 3

What command do we use to run a script?

Teacher
Teacher Instructor

Good question! We use `eng.run('myscript.m', nargout=0)`. The `nargout=0` indicates that we don't expect any output back from the script.

Student 4
Student 4

Can we pass parameters into that script?

Teacher
Teacher Instructor

Yes! We can set variables in the MATLAB workspace from Python, like `eng.workspace['x'] = 42`, so the script can use it. This is pretty powerful!

Teacher
Teacher Instructor

To summarize, we import the MATLAB engine, start it, run our scripts, and pass parameters directly into MATLAB’s workspace.

Extracting Results from MATLAB Workspace

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Now that we know how to run scripts, let’s discuss how we can retrieve results after execution. What's an example of getting back a variable from MATLAB?

Student 1
Student 1

Would it be something like `result = eng.workspace['y']`?

Teacher
Teacher Instructor

Perfect! This line retrieves the variable 'y' from the MATLAB workspace back into Python. This allows us to use MATLAB’s calculations in our Python environment.

Student 2
Student 2

What kind of data can we get back?

Teacher
Teacher Instructor

Great follow-up! You can retrieve various data types, such as numbers, arrays, and even strings. Just be mindful of the data type conversions between Python and MATLAB!

Student 3
Student 3

Can you give us an example of all this?

Teacher
Teacher Instructor

Sure! For instance, if you modify `y` based on some input `x` in your MATLAB script, after execution, you might access `result` in Python and use it for further analysis.

Teacher
Teacher Instructor

In summary, we can pass parameters into our scripts, run them, and extract results back into our Python code efficiently.

Practical Implementation Example

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Let’s look at a simple implementation. Imagine you have a MATLAB script that computes the sum of an array. How would we set that up in Python?

Student 4
Student 4

We start with importing the MATLAB engine and then run the script?

Teacher
Teacher Instructor

Correct! And we’d also need to prepare the input array in Python, converting it to the appropriate MATLAB type first.

Student 1
Student 1

How do we convert it to MATLAB type?

Teacher
Teacher Instructor

You would use `matlab.double()` to convert a Python list, for example. This handles the data type difference.

Student 2
Student 2

And after we run the script, we can retrieve the sum in Python?

Teacher
Teacher Instructor

Yes! Once your script finishes running, you'll access the output variable to retrieve the result. Always ensure your script outputs as expected, and you check the types when extracting!

Teacher
Teacher Instructor

As a summary, always convert your inputs correctly, run the script, and extract your results into Python for further use.

Introduction & Overview

Read summaries of the section's main ideas at different levels of detail.

Quick Overview

This section explains how to execute MATLAB scripts in Python, allowing parameter passing and workspace interaction.

Standard

In this section, you'll learn about how to run MATLAB .m scripts directly from Python using the MATLAB Engine API. It covers key commands for executing scripts, passing parameters, and retrieving results from the MATLAB workspace.

Detailed

Executing MATLAB Scripts in Python

In this section, we explore how to effectively execute MATLAB scripts (.m files) from within Python using the MATLAB Engine API, which provides seamless interaction between the two programming environments. The main command used for running a MATLAB script is eng.run('myscript.m', nargout=0), where eng is the MATLAB engine instance previously started. Additionally, you can pass parameters into the MATLAB workspace using commands like eng.workspace['x'] = 42 to set variables accessed by the script. After executing the script, results can be extracted back to Python using result = eng.workspace['y']. This integration allows users to take advantage of MATLAB's powerful numerical capabilities while leveraging Python's flexibility, ultimately enhancing productivity in scientific computing.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Executing MATLAB Scripts

Chapter 1 of 3

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

• MATLAB .m scripts can be executed using:
• eng.run('myscript.m', nargout=0)

Detailed Explanation

In this step, we learn how to execute MATLAB scripts directly from Python. The main command we need is eng.run('myscript.m', nargout=0) which runs the specified MATLAB script with the name 'myscript.m'. The nargout=0 parameter indicates that we do not expect any outputs to be returned from this function call.

Examples & Analogies

Think of it like sending a chef a handwritten recipe (your MATLAB script) to cook a dish. You do not need to see the dish made (no output needed), but you trust the chef (MATLAB) to execute the instructions properly.

Passing Parameters to MATLAB

Chapter 2 of 3

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

• Parameters can be passed via workspace:
• eng.workspace['x'] = 42
eng.eval('y = x + 10;', nargout=0)

Detailed Explanation

This chunk explains how we can pass parameters from Python to MATLAB. We first set a value in the MATLAB workspace by using eng.workspace['x'] = 42, which essentially creates a variable 'x' in MATLAB with a value of 42. We can then use eng.eval('y = x + 10;', nargout=0) to perform a calculation where MATLAB creates a new variable 'y' that is the result of 'x + 10'. Here, we're again indicating we do not expect a result back with nargout=0.

Examples & Analogies

Imagine you are sending a grocery list (parameter 'x') to a friend (MATLAB) and then asking them to prepare a meal using the grocery items you specified,, like adding an extra ingredient (10) to your original list. You don’t need to see what they concoct; you trust them to follow your list.

Retrieving Results from MATLAB

Chapter 3 of 3

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

• result = eng.workspace['y']

Detailed Explanation

In this final chunk, we discuss how to retrieve results from MATLAB back into Python. After running our calculations in MATLAB, we can access the results by accessing the MATLAB workspace directly. The command result = eng.workspace['y'] will fetch the value of variable 'y' from MATLAB and store it in a Python variable called 'result'.

Examples & Analogies

This step is like checking back with your friend after they tell you about the meal they made using the ingredients from the grocery list. You ask them about the final dish (variable 'y') and they let you know how it turned out (the result in Python).

Key Concepts

  • MATLAB Engine API: An interface that facilitates communication between Python and MATLAB.

  • Running Scripts: The command used to execute .m files from Python.

  • Workspace Interaction: The ability to pass and retrieve variables between Python and MATLAB.

Examples & Applications

Using eng.run('myscript.m', nargout=0) to execute a MATLAB script.

Passing a parameter with eng.workspace['x'] = 42 before running the script.

Memory Aids

Interactive tools to help you remember key concepts

🎵

Rhymes

Run your script with eng.run, it's really easy and a lot of fun!

📖

Stories

Imagine Python as an assistant who fetches and executes tasks given by MATLAB, waiting eagerly for results to come back.

🧠

Memory Tools

Remember RRP: Run it, Retrieve it, Pass parameters.

🎯

Acronyms

PIG

Python Interacting with MATLAB via the MATLAB Engine.

Flash Cards

Glossary

MATLAB Script

A script written for MATLAB, with a .m file extension, used for numerical computations.

MATLAB Engine API

An interface that allows Python scripts to interact with a MATLAB session.

nargout

A parameter used in MATLAB to specify the number of output arguments to return.

workspace

The environment in MATLAB where variables are stored and can be accessed during operations.

Reference links

Supplementary resources to enhance your learning experience.