十多年前曾經有參加過一個案子會用 c# 呼叫 matlab 函數, 最近又被問到以前的考古問題早就都忘光光了, 還好現在是學生可以免費蹭 matlab XD
開啟 matlab 在選單找到 APPS => Get More Apps
接著安裝 MATLAB Compiler MATLAB Compiler SDK
他新版跟舊版作法又不太一樣, 舊版叫做 MWArray API 新版則是 MATLAB Data API for .NET
先建立一個 matlab 函數, 檔名為 add_two_numbers
1 | function result = add_two_numbers(a, b) |
點選 APPS => .NET Assembly Compiler
點選 Exported Functions => Add Exported Function 把 add_two_numbers 函數加入
MATLAB Data API for .NET
點選 .NET API Selection => Create interface that uses the MATLAB Data API for .NET
點選 Assembly Options => .NET 5.0 or higher
點選 Installer Details => Do not include MATLAB Runtime in application Installer
然後選擇編譯, 他會建立一個 c# csproj, 可以直接在 solution 底下直接建個新的 console 專案
引入剛剛 matlab 編譯好的專案
接著看看自己電腦是否有 matlab 沒的話請使用 runtime
runtime 可以在這裡下載 https://www.mathworks.com/products/compiler/matlab-runtime.html
If MATLAB is installed on your system
matlabroot\extern\dotnet\netstandard2.0\MathWorks.MATLAB.Runtime.dll
matlabroot\extern\dotnet\netstandard2.0\MathWorks.MATLAB.Types.dll
If MATLAB Runtime is installed on your system
<MATLAB_RUNTIME_INSTALL_DIR>\extern\dotnet\netstandard2.0\MathWorks.MATLAB.Types.dll
我環境的位置在 C:\Program Files\MATLAB\R2025b\extern\dotnet\netstandard2.0
加入參考 MathWorks.MATLAB.Types.dll MathWorks.MATLAB.Runtime.dll
或參考這個 官方範例 去調整 csproj
1 | <Project Sdk="Microsoft.NET.Sdk"> |
貼上以下程式碼即可
1 | // See https://aka.ms/new-console-template for more information |
MWArray API
點選 .NET API Selection => Create interface that uses the mwArray API for .NET
點選 Assembly Options => .NET 4.x(.NET framework)
點選 Installer Details => Do not include MATLAB Runtime in application Installer
要調整類別名稱的話則選 Build Settings => Class info
編譯之後請自己開一個 .net framework 的 console 並且引入剛剛編譯好的 dll
另外還需要引入 MWArray.dll 它的位置在 C:\Program Files\MATLAB\R2025b\toolbox\dotnetbuilder\bin\win64\netstandard2.0
特別注意到他這裡是 win64 c# 專案也要用 x64 如果你的環境是 x86 則記得選則 x86 不然會噴 error 噴到死 ~~~
最後記得要改成 x64 不然會噴 error!
最後記得要改成 x64 不然會噴 error!
最後記得要改成 x64 不然會噴 error!
最後記得要改成 x64 不然會噴 error!
最後記得要改成 x64 不然會噴 error!
最後貼上以下程式碼即可
1 | using System; |