Created
October 1, 2025 18:45
-
-
Save Bogd-an/fe84b09f8fc8a5fef9eb3c1d6ddd7faa to your computer and use it in GitHub Desktop.
matlab in jupiter notebook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # хоч і працює, але повільно і згодом ядро крашиться | |
| import os | |
| import subprocess | |
| import sys | |
| import json | |
| import ctypes | |
| # ---------------- Перевірка на адміністратора ---------------- | |
| def is_admin(): | |
| try: | |
| return ctypes.windll.shell32.IsUserAnAdmin() | |
| except: | |
| return False | |
| if not is_admin(): | |
| print("[WARNING] Скрипт не запущено з правами адміністратора!") | |
| print("Щоб уникнути помилок при встановленні MATLAB Engine, закрийте VS Code і запустіть його як Адміністратор.") | |
| input("Натисніть Enter, щоб продовжити скрипт (можливо, він упаде при установці MATLAB Engine)...\n") | |
| # ---------------- ПАРАМЕТРИ ---------------- | |
| venv_dir = ".venv" | |
| matlab_path = r"C:\Program Files\MATLAB\R2023b" | |
| imatlab_dir = "imatlab_temp" | |
| notebook_file = "HelloMATLAB.ipynb" | |
| python_exe = sys.executable | |
| # ---------------- КРОК 1: Створення віртуального середовища ---------------- | |
| if os.path.exists(venv_dir): | |
| print(f"[INFO] Віртуальне середовище '{venv_dir}' вже існує. Пропускаємо створення.") | |
| else: | |
| print(f"[INFO] Створюємо віртуальне середовище '{venv_dir}'...") | |
| subprocess.check_call([python_exe, "-m", "venv", venv_dir]) | |
| print("[OK] Віртуальне середовище створено!") | |
| venv_python = os.path.join(venv_dir, "Scripts", "python.exe") | |
| venv_pip = os.path.join(venv_dir, "Scripts", "pip.exe") | |
| # ---------------- КРОК 2: Оновлення pip ---------------- | |
| print("[INFO] Оновлюємо pip...") | |
| subprocess.check_call([venv_python, "-m", "pip", "install", "--upgrade", "pip"]) | |
| print("[OK] pip оновлено!") | |
| # ---------------- КРОК 3: Встановлення Jupyter та сумісної версії ipykernel ---------------- | |
| packages = ["jupyter", "gitpython", "ipykernel<6"] | |
| print("[INFO] Встановлюємо Jupyter, gitpython та сумісний ipykernel...") | |
| subprocess.check_call([venv_pip, "install"] + packages) | |
| print("[OK] Пакети встановлено!") | |
| # ---------------- КРОК 4: Встановлення MATLAB Engine API ---------------- | |
| engine_dir = os.path.join(matlab_path, "extern", "engines", "python") | |
| if not os.path.exists(engine_dir): | |
| print(f"[ERROR] MATLAB Engine API не знайдено за шляхом: {engine_dir}") | |
| sys.exit(1) | |
| print("[INFO] Встановлюємо MATLAB Engine API у віртуальному середовищі...") | |
| subprocess.check_call([venv_python, "-m", "pip", "install", engine_dir]) | |
| print("[OK] MATLAB Engine встановлено!") | |
| import shutil | |
| # ---------------- КРОК 5: Клонування та встановлення iMATLAB ---------------- | |
| if not os.path.exists(imatlab_dir): | |
| print("[INFO] Клонуємо iMATLAB kernel...") | |
| subprocess.check_call(["git", "clone", "https://github.com/imatlab/imatlab.git", imatlab_dir]) | |
| print("[OK] iMATLAB клоновано!") | |
| print("[INFO] Встановлюємо iMATLAB kernel у .venv ...") | |
| subprocess.check_call([venv_python, "setup.py", "install"], cwd=imatlab_dir) | |
| print("[OK] iMATLAB встановлено!") | |
| # ---------------- КРОК 5.1: Видалення тимчасової папки ---------------- | |
| try: | |
| shutil.rmtree(imatlab_dir) | |
| print(f"[INFO] Тимчасова папка '{imatlab_dir}' видалена.") | |
| except Exception as e: | |
| print(f"[WARNING] Не вдалося видалити '{imatlab_dir}': {e}") | |
| # ---------------- КРОК 6: Реєстрація MATLAB kernel ---------------- | |
| print("[INFO] Реєструємо MATLAB kernel для Jupyter...") | |
| env = os.environ.copy() | |
| env["MATLAB_INSTALL_PATH"] = matlab_path | |
| subprocess.check_call([venv_python, "-m", "imatlab", "install"], env=env) | |
| print("[OK] MATLAB kernel зареєстровано!") | |
| # ---------------- КРОК 7: Створення простого notebook ---------------- | |
| print(f"[INFO] Створюємо notebook '{notebook_file}' з MATLAB кодом...") | |
| notebook_content = { | |
| "cells": [ | |
| { | |
| "cell_type": "code", | |
| "metadata": {"kernel": "imatlab"}, | |
| "source": [ | |
| "disp('hello world');" | |
| ], | |
| "execution_count": None, | |
| "outputs": [] | |
| } | |
| ], | |
| "metadata": { | |
| "kernelspec": { | |
| "display_name": "MATLAB", | |
| "language": "matlab", | |
| "name": "imatlab" | |
| }, | |
| "language_info": { | |
| "name": "matlab" | |
| } | |
| }, | |
| "nbformat": 4, | |
| "nbformat_minor": 5 | |
| } | |
| with open(notebook_file, "w", encoding="utf-8") as f: | |
| json.dump(notebook_content, f, indent=2, ensure_ascii=False) | |
| print(f"[OK] Notebook '{notebook_file}' створено! Можна відкрити у VS Code та запускати MATLAB kernel.\n") | |
| print(f"[INFO] Щоб активувати віртуальне середовище: {venv_dir}\\Scripts\\activate") | |
| print("[INFO] Потім запускати Jupyter Notebook: jupyter notebook") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment