如何用VBA代码向MATLAB传递参数

eagi6jfj  于 2023-01-09  发布在  Matlab
关注(0)|答案(1)|浏览(309)

我正在尝试通过Excel运行MATLAB。需要在MATLAB中使用的数据位于Excel工作表中。因此,我在MATLAB中编写了一段代码,用于从Excel工作表中读取数据并绘制三元图。MATLAB中的代码为:

opts = spreadsheetImportOptions("NumVariables", 15);

opts.Sheet = "TernaryPlot1";

opts.DataRange = "A8:O20";

opts.VariableNames = ["Var1", "Var2", "Var3", "Var4", "Var5", "Var6", 
"Var7", "Var8", "Var9", "Var10", "Var11", "W4", "W5", "W6", 
"NormalizedResault"];

opts.SelectedVariableNames = ["W4", "W5", "W6", "NormalizedResault"];

opts.VariableTypes = ["char", "char", "char", "char", "char", "char", 
"char", "char", "char", "char", "char", "double", "double", "double", 
"double"];

opts = setvaropts(opts, ["Var1", "Var2", "Var3", "Var4", "Var5", "Var6", 
"Var7", "Var8", "Var9", "Var10", "Var11"], "WhitespaceRule", 
"preserve");

opts = setvaropts(opts, ["Var1", "Var2", "Var3", "Var4", "Var5", "Var6", 
"Var7", "Var8", "Var9", "Var10", "Var11"], "EmptyFieldRule", "auto");

opts = setvaropts(opts, ["W4", "W5", "W6", "NormalizedResault"], 
"FillValue", 0);

% Import the data

B = readtable("Path of my Excell folder ", opts, "UseExcel", false);

clear opts

% % Main file for ternary plot

A=table2array(B)

 warning off MATLAB:griddata:DuplicateDataPoints

l=length(A);

v=0.29./sqrt(A(:,4));

figure;

colormap(jet)
[hg,htick,hcb]=tersurf(A(:,1),A(:,2),A(:,3),A(:,4));

hlabels=terlabel('Weight on First goal','Weight on Second Goal','Weight 
on Third Goal');

citra3=montage(reshape(V,size(citra)),map,'Indices',3);

我通过VBA调用上述MATLAB代码,代码如下:

Dim MatLab As Object

Dim fileToRun As String

Dim matlabCommand As String

%% Open the Matlab program

Set MatLab = CreateObject("Matlab.Application")

MatLab.Execute ("input('Please press enter to continue');")

Dim PathCrnt As String

PathCrnt = ActiveWorkbook.Path

fileToRun = PathCrnt & "name of Matlab code that I mentioned above"

matlabCommand = "matlab -nodisplay -nosplash -nodesktop -r "" run('" & 
fileToRun & "');exit;"" "

Shell (matlabCommand)

End Sub

正如您在代码的第一部分所看到的,我使用的是excel工作表的特定地址。但是,需要将此地址泛化,以便任何用户都可以使用。我在此之前已经问过这个问题,他们建议我在调用期间将excel路径作为参数传递给Matlab(代码的第二部分)基于代码的第二部分,包含地址的参数是“PathCrnt”但我对VBA了解不多。因此,如果您能帮我找到一个代码,可以通过VBA将参数传递给MATLAB,我将不胜感激。

nxowjjhe

nxowjjhe1#

您可以更改Matlab代码,在函数的开头添加一个输入参数,例如“excelPath”,然后更改matlabCommand字符串的VBA代码,将该参数作为MatLab函数的输入参数。
matlab命令=“matlab -无显示-无飞溅-无桌面-r“”运行('"要运行的文件',”“Excel路径&“);退出;"”“
&将excelPath变量连接为输入参数,如果您在Matlab代码中使用此变量而不是您已经定义的路径,则可能有助于修复此问题。

相关问题