在 C++Builder 中呼叫 MATLAB 工具箱函數有兩種路徑:依賴 MATLAB 環境或完全脫離 MATLAB 使用 Mediva 平台。Mediva (MathTools) 提供 MATLAB 基礎函數解譯執行環境與 M 檔轉 DLL 編譯功能,版本 4.5 僅 6.5MB,支援 Borland C++、VB、Delphi。本文詳述直接呼叫 MATLAB 函數與工具箱函數轉 DLL 兩種模式。
implib mdv4300.lib mdv4300.dll,連同 ago4300.dll 放入專案目錄。#include "matlib.h" 必須置於第一行,定義所有型別、常數、函數宣告。plot(x,'r') → C++ plot(CL(x), TM("r")),CL 標示多變數輸入,TM 標示字串。#include "matlib.h"
#include <vcl.h>
#pragma hdrstop
#include "TryMatcomU.h"
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {}
void __fastcall TForm1::Button1Click(TObject *Sender) {
initM(MATCOM_VERSION);
Mm cur1 = zeros(128), cur2 = zeros(128);
for (int k=1; k<=128; k++) cur1.r(k) = randM();
figure(1); plot(cur1);
cur2 = fft(cur1, 128);
figure(2); stem(CL(cur1), real(cur2), TM("r")); // 火柴棒圖
exitM();
}
flower.cpp/h、g_flower.cpp。g_flower.cpp 中 in01 宣告錯誤,並撰寫 .mak 編譯連結。new Mm())。extern "C" {
void DLLX _stdcall flower_1_1(Mm in01, Mm **out01) {
*out01 = new Mm(); **out01 = flower(in01); exitM();
}
void DLLX _stdcall flower_1_2(Mm in01, Mm **out01, Mm **out02) {
*out01 = new Mm(); *out02 = new Mm();
flower(in01, i_o, **out01, **out02); exitM();
}
}