【发布时间】:2019-05-08 12:24:35
【问题描述】:
(在最新的 windows10 下使用 Matlab 2018b。)我有一个文件夹 Folder 包含 DoStuff.m,其代码是:
%addpath('./SubFolder/SubSubFolder'); // SubSubFolder contains mex file defining myFunction used below
%close all;
function [res] = DoStuff(param) % Function has same name as the script defining it
res = myFunction(param)
end
其中myFunction 定义在mexw64 文件中,该文件包含在'./SubFolder/SubSubFolder' 中。
当然,在 Matlab 的 GUI(文件夹 Folder)中执行函数 DoStuff(param) 会引发以下错误:
'myFunction' is not found in the current folder or on the MATLAB path, but exists in ...
...在'./SubFolder/SubSubFolder'。高超。因此,我删除了DoStuff.m 第一行中的% 并在Matlab 的GUI 中(在文件夹Folder 中)重新执行函数DoStuff(param) 并得到以下错误:
Function with duplicate name "DoStuff" cannot be defined.
奇怪,DoStuff 只在一个地方定义:在DoStuff.m 脚本中。 (由 Folder 中的 Matlab 中的 which -all DoStuff 确认。)
备注。在 Matlab2018b 中,可以在名为 toto.m 的脚本中定义一个名为 toto 的函数,Matlab 不会有任何问题。所以我的问题与相同的命名无关。它与添加addpath 行有关,但我不知道怎么做。确认这种感觉:用res = 1 替换行res = myFunction(param) 并取消注释添加路径也会导致命名错误。
【问题讨论】:
-
那句话是完全错误的,是基于误解。尝试使用名称 DoStuff.m 保存 this code 并运行它。看看你得到了什么。您不能在名为
toto的脚本中定义名为toto的函数。如果在定义函数之前脚本中没有可执行行,那么它是函数文件而不是脚本文件,因此完全没问题 -
我建议,正如我在回答您之前的问题时所做的那样,将 MEX 文件放入
Folder/private。private是一种特殊的目录,您不需要添加到路径中。其中的函数只能被Folder中的函数访问。 -
addpath会全局影响 MATLAB。您不能仅更改一项功能的路径。此外,它会带来很大的开销,因为 MATLAB 需要索引添加到路径中的目录。如果你想重复调用它,你调用 MEX 文件的 M 文件不应该有这个开销。