Close Menu
  • AI
  • Content Creation
  • Tech
  • Robotics
AI-trends.todayAI-trends.today
  • AI
  • Content Creation
  • Tech
  • Robotics
Trending
  • 5 Reasons to Think Twice Before Using ChatGPT—or Any Chatbot—for Financial Advice
  • OpenAI Releases GPT-5.5, a Absolutely Retrained Agentic Mannequin That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval
  • Your Favorite AI Gay Thirst Traps: The Men Behind them
  • Mend Releases AI Safety Governance Framework: Masking Asset Stock, Danger Tiering, AI Provide Chain Safety, and Maturity Mannequin
  • Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Coaching Structure Attaining 88% Goodput Below Excessive {Hardware} Failure Charges
  • Mend.io releases AI Security Governance Framework covering asset inventory, risk tiering, AI Supply Chain Security and Maturity model
  • Stanford Students Wait in Line to Hear From Silicon Valley Royalty at ‘AI Coachella’
  • Google Cloud AI Research introduces ReasoningBank: a memory framework that distills reasoning strategies from agent successes and failures.
AI-trends.todayAI-trends.today
Home»Tech»Connect Octave to the oct2py Libary and Run MATLAB Style Code in Python

Connect Octave to the oct2py Libary and Run MATLAB Style Code in Python

Tech By Gavin Wallace20/09/20256 Mins Read
Facebook Twitter LinkedIn Email
NVIDIA AI Introduces AceReason-Nemotron for Advancing Math and Code Reasoning
NVIDIA AI Introduces AceReason-Nemotron for Advancing Math and Code Reasoning
Share
Facebook Twitter LinkedIn Email

This tutorial explores how to run MATLAB code in Python using the oct2py libraries. The environment is set up on Google Colab. We exchange data with NumPy/Octave, call and write.m files and visualize plots produced in Octave using Python. This allows us to take advantage of the Python ecosystem, while still leveraging the numerical and syntax power of MATLAB/Octave. See the FULL CODES here.

!apt-get -qq update
!apt-get -qq install -y octave gnuplot octave-signal octave-control > /dev/null
Install oct2py, scipy, matplotlib and pillow with!python.


From oct2py: import Oct2Py. Oct2PyError
Import numpy, matplotlib.pyplot and textwrap as the appropriate nps.
Import savemat and loadmat from scipy.io
PIL Import Image


Oct2Py = oc()
print("Octave version:", oc.eval("version"))


Def show_png (path, title=None),
 Img = Image.open (path)
   plt.figure(figsize=(5,4)); plt.imshow(img); plt.axis("off")
 If title is plt.title, then the following code will be used:
   plt.show()

In Google Colab we first install Octave, and then the essential libraries. We also ensure that Python and Octave packages are ready. After initializing an Oct2Py sessions, we define a helper method to allow us to directly display Octave generated plots within our Python workflow. Visit the FULL CODES here.

print("n--- Basic eval ---")
print(oc.eval("A = magic(4); A"))
print("eig(A) diag:", oc.eval("[V,D]=eig(A); diag(D)'"))
print("sin(pi/4):", oc.eval("sin(pi/4)"))


print("n--- NumPy exchange ---")
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x) + 0.1*np.random.randn(x.size)
y_filt = oc.feval("conv", y, np.ones(5)/5.0, "same") 
print("y_filt shape:", np.asarray(y_filt).shape)


print("n--- Cells & Structs ---")
Cells = ["hello", 42, [1,2,3]]
oc.push("C", cells)
oc.eval("s = struct('name','Ada','score',99,'tags',{C});")
s = oc.pull("s")
print("Struct from Octave -> Python:", s)

We then test the Python to Octave Bridge by running matrix operations such as eigenvalues decomposition and trigonometric computations in Octave. NumPy and Octave are then used to create a convolutional filter. We show you how to send Python lists in Octave and build a struct. Then, retrieve the struct back into Python. Visit the FULL CODES here.

print("n--- Writing and calling .m files ---")
gd_code gd_code r"""
Enjoy the benefits of a function [w, hist] = gradient_descent(X, y, alpha, iters)
 % X: (n,m), y: (n,1). This adds bias, returns the weights of losses and history.
 If size(X,2) >= 0, Error('X Must Be 2D'); End
 Rows = (n)
 The Xb is the same as the xb [ones(n,1), X];
 Columns(Xb) = m
 w = zeros(m,1);
 hist = zeros(iters,1);
 For t=1:iters
   yhat = Xb*w;
   g = (Xb'*(yhat - y))/n;
   w = w - alpha * g;
   hist(t) = (sum((yhat - y).^2)/(2*n));
 No end for the day
Endfunction
"""
With open("gradient_descent.m","w") as f: f.write(textwrap.dedent(gd_code))


np.random.seed(0)
X = random.randn.np(200, 3).
true_w = np.array([2.0, -1.0, 0.5, 3.0])    
y = false_w[0] + X @ True_w[1:] + 0.3*np.random.randn(200)
w_est, hist = oc.gradient_descent(X, y.reshape(-1,1), 0.1, 100, nout=2)
print("Estimated w:", np.ravel(w_est))
print("Final loss:", float(np.ravel(hist)[-1]))


print("n--- Octave plotting -> PNG -> Python display ---")
oc.eval("x = linspace(0,2*pi,400); y = sin(2*x) .* exp(-0.2*x);")
oc.eval("figure('visible','off'); plot(x,y,'linewidth',2); grid on; title('Damped Sine (Octave)');")
plot_path = "/content/oct_plot.png"
oc.eval(f"print('{plot_path}','-dpng'); close all;")
show_png(plot_path, title="Octave-generated Plot")

This is done by writing a gradient_descent.m custom in Octave. It’s then called from Python using nout=2, to confirm we get reasonable weights, and that the loss decreases. This is done by rendering a damped sin plot as an off-screen Octave Figure and displaying the PNG saved in line in our Python Notebook. Click here to see the FULL CODES here.

print("n--- Packages (signal/control) ---")
signal_ok= True
try:
   oc.eval("pkg load signal; pkg load control;")
   print("Loaded: signal, control")
except Oct2PyError as e:
 Signal_ok = FALSE
   print("Could not load signal/control, skipping package demo.nReason:", str(e).splitlines()[0])


If signal_ok
   oc.push("t", np.linspace(0,1,800))
   oc.eval("x = sin(2*pi*5*t) + 0.5*sin(2*pi*40*t);")
   oc.eval("[b,a] = butter(4, 10/(800/2)); xf = filtfilt(b,a,x);")
   xf = oc.pull("xf")
   plt.figure(); plt.plot(xf); plt.title("Octave signal package: filtered"); plt.show()


print("n--- Function handles ---")
oc.eval("""
f = @(z) z.^2 + 3*z + 2;
vals = feval(f, [0 1 2 3]);
""")
vals=oc.pull"vals")
print("f([0,1,2,3]) =", np.ravel(vals))


Quadfun_code = R"""
function y = quadfun(z)
 y = z.^2 + 3*z + 2;
The end of the world is near.
"""
With open("quadfun.m","w") as f: f.write(textwrap.dedent(quadfun_code))
vals2 = oc.quadfun(np.array([0,1,2,3], dtype=float))
print("quadfun([0,1,2,3]) =", np.ravel(vals2))

We then load both the control and signal packages to design a Butterworth filters in Octave. Finally, we visualize the filtered waves in Python. Also, to demonstrate robustness and handle-based calls, we create a file named quadfun.m and call it from Python. Visit the FULL CODES here.

print("n--- .mat I/O ---")
data_py = {"A": np.arange(9).reshape(3,3), "label": "demo"}
savemat("demo.mat", data_py)
oc.eval("load('demo.mat'); A2 = A + 1;")
oc.eval("save('-mat','demo_from_octave.mat','A2','label');")
Back = Loadmat"demo_from_octave.mat")
print("Keys from Octave-saved mat:", list(back.keys()))


print("n--- Error handling ---")
try:
   oc.eval("no_such_function(1,2,3);")
except Oct2PyError as e:
   print("Caught Octave error as Python exception:n", str(e).splitlines()[0])


print("n--- Simple Octave benchmark ---")
oc.eval("N = 2e6; a = rand(N,1);")


oc.eval("tic; s1 = sum(a); tv = toc;")
t_vec = float(oc.pull("tv"))


oc.eval("tic; s2 = 0; for i=1:length(a), s2 += a(i); end; tl = toc;")
t_loop = float(oc.pull("tl"))


print(f"Vectorized sum: {t_vec:.4f}s | Loop sum: {t_loop:.4f}s")


print("n--- Multi-file pipeline ---")
pipeline_m = r"""
Function out = mini_pipeline (x, fs).
 Catch the end of the signal when you try to pkg-load.
 [b,a] = butter(6, 0.2);
 y = filtfilt(b,a,x);
 y_env = abs(hilbert(y));
 out = struct y_env (y_env(1):10), "peak", max(abs()y), "rms", sqrt (mean(y.2)),
The end of the world is near.
"""
With open("mini_pipeline.m","w") as f: f.write(textwrap.dedent(pipeline_m))


fs = 200.0
sig = np.sin(2*np.pi*3*np.linspace(0,3,int(3*fs))) + 0.1*np.random.randn(int(3*fs))
out = oc.mini_pipeline(sig, fs, nout=1)
print("mini_pipeline -> keys:", list(out.keys()))
print("RMS ~", float(out["rms"]), "| Peak ~", float(out["peak"]), "| env head:", np.ravel(out["env"])[:5])


print("nAll sections executed. You are now running MATLAB/Octave code from Python!")

We test data flow by exchanging.mat files from Python to Octave. We test the error handling as well by catching Octave errors in Python. We then compare vectorized summations to looped ones in Octave and show the superior performance of vectorization. We built a pipeline of multiple files that apply envelope detection and filtering, while returning important statistics to Python. This shows how we can organise Octave code as reusable components in our Python workflow.

We conclude by showing how we can directly integrate Octave’s MATLAB compatible features into Python and Colab. Data exchange, plotting and package usage are all successfully tested. We also demonstrate that we can combine MATLAB/Octave with Python workflows without having to leave our notebook. Combining the strengths of these two environments allows us to work more effectively and efficiently.


Take a look at the FULL CODES here. Please feel free to browse our GitHub Page for Tutorials, Codes and Notebooks. Also, feel free to follow us on Twitter Don’t forget about our 100k+ ML SubReddit Subscribe Now our Newsletter.


Asif Razzaq serves as the CEO at Marktechpost Media Inc. As an entrepreneur, Asif has a passion for harnessing Artificial Intelligence to benefit society. Marktechpost was his most recent venture. This platform, which focuses on machine learning and deep-learning news, is technically solid and accessible to a broad audience. Over 2 million views per month are a testament to the platform’s popularity.

🔥[Recommended Read] NVIDIA AI Open-Sources ViPE (Video Pose Engine): A Powerful and Versatile 3D Video Annotation Tool for Spatial AI

Share. Facebook Twitter LinkedIn Email
Avatar
Gavin Wallace

Related Posts

OpenAI Releases GPT-5.5, a Absolutely Retrained Agentic Mannequin That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval

24/04/2026

Mend Releases AI Safety Governance Framework: Masking Asset Stock, Danger Tiering, AI Provide Chain Safety, and Maturity Mannequin

24/04/2026

Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Coaching Structure Attaining 88% Goodput Below Excessive {Hardware} Failure Charges

24/04/2026

Mend.io releases AI Security Governance Framework covering asset inventory, risk tiering, AI Supply Chain Security and Maturity model

23/04/2026
Top News

Do Large Language Models (LLMs), or just good at simulating intelligence, represent real AI? • AI Blog

Google AI search loves to refer you back to Google

X Didn’t Fix Grok’s ‘Undressing’ Problem. You just make people pay for it

Watch our next livestream: School Returns in an Age of AI

The Way forward for AI Filmmaking Is a Parody of the Apocalypse, Made by a Man Named Josh

Load More
AI-Trends.Today

Your daily source of AI news and trends. Stay up to date with everything AI and automation!

X (Twitter) Instagram
Top Insights

Big Tech’s White House Data Center Signs Pledge with Good Optical and Little Substance

04/03/2026

Gemini Flash, Few Shot Selection and Evolutionary Instruction Search: A complete workflow for automated prompt optimization

19/12/2025
Latest News

5 Reasons to Think Twice Before Using ChatGPT—or Any Chatbot—for Financial Advice

24/04/2026

OpenAI Releases GPT-5.5, a Absolutely Retrained Agentic Mannequin That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval

24/04/2026
X (Twitter) Instagram
  • Privacy Policy
  • Contact Us
  • Terms and Conditions
© 2026 AI-Trends.Today

Type above and press Enter to search. Press Esc to cancel.