如何找到当前 运行 代码的文件扩展名?

How can I find the file extension of the currently running code?

MATLAB 提供 mfilename function. It returns the name of the file where the function was invoked, but unfortunately, it returns the file name without the extension.

因此,例如,如果我们有一个名为 myfile.m 的文件,并且我们在文件中调用 mfilename,它将 return 字符串 'myfile' 而不是 'myfile.m'

我也查看了 fileparts 函数,但它也没有用,因为它只解析您提供的字符串。

我正在开发一段根据文件扩展名具有不同行为的代码。因此,例如,它需要知道文件的扩展名是 .m 还是 .p at run time.

您可以查看与 MATLAB 关联的扩展列表 here

我该怎么做?

Looking at the docs,看来你可以从dbstack命令中得到你需要的信息,不过需要一些小的额外处理。

[ST, I] = dbstack('-completenames', 1)

ST = 

    file: 'C:\myProject\myfile.m'
    name: 'myfile'
    line: 2