【问题标题】:Matlab variable which stores the name of the mfile and line numberMatlab 变量,用于存储 mfile 的名称和行号
【发布时间】:2016-08-06 12:25:26
【问题描述】:

出于调试目的,我想打印出 m 文件的名称和行号,以便在出现问题时显示类似

Error at 197th line of run.m

鉴于 Matlab 显示了这种类型的错误消息,必须有解决方案。

我该怎么做?

===========后续问题==============

谢谢!但我有一个后续问题。

我有 main.m,它是主 m 文件,而 main.m 调用 lower.m

我写了

info = dbstack()

try 
    error('Toto')
catch ME
    ME.stack
end

到 main.m。然后matlab显示

info = 

    file: 'main.m'
    name: 'main'
    line: 15

ans = 

    file: 'C:\Users\account1\Google Drive\1AAA-RA\11HHJK(O…'
    name: 'main'
    line: 18

但是,当我将 dbstack 和 try-catch 的东西写到 lower.m 时,Matlab 不会显示任何确切的信息。

我运行了 main.m 和 main.m 称为较低级别的 m 文件,但它不显示任何信息。

info = 

2x1 struct array with fields:

    file
    name
    line

ans = 

2x1 struct array with fields:

    file
    name
    line

如何让它显示每个文件、名称、行信息?

理想情况下,Matlab 会同时显示 main.m 和 lower.m 的信息,如下所示:

    file1: 'main.m'
    name1: 'main'
    line1: 15
    file2: 'lower.m'
    name2: 'lower'
    line2: 6

这可能吗?

【问题讨论】:

  • 是的,您在结构中有可用的信息:info = 2x1 struct 带有字段的数组:。尝试在命令窗口中输入info(1)。另外,请阅读有关访问structure 字段的信息...

标签: matlab


【解决方案1】:

您可以使用 Matlab 异常对象。行信息包含在“堆栈”属性中。

例如创建一个“test.m”脚本:

try
    error('Toto')
catch ME
    ME.stack
end

命令窗口的输出是:

>> test

ans = 

    file: 'D:\MATLAB\Sandboxes\AVLab\test.m'
    name: 'test'
    line: 2

或者没有 try/catch 你可以使用 MException.last。

查看文档链接http://www.mathworks.com/help/matlab/matlab_prog/capture-information-about-errors.html

【讨论】:

  • 谢谢!您的解决方案有效。但是当我将它写入较低级别的 m 文件时它不起作用。我运行了 main.m 和 main.m 称为较低级别的 m 文件,但它不显示任何信息。
【解决方案2】:
info = dbstack();

% info is now a struct that has 3 fields

% info.file
% is a string containing the file name in which the function appears.

% info.name 
% is a string containing the name of the function within the file.

% info.line
% is the line number on which dbstack was called

【讨论】:

  • 再次感谢牙签海葵!您的解决方案有效。但是当我将它写入较低级别的 m 文件时它不起作用。我运行了 main.m 和 main.m 称为较低级别的 m 文件,但它不显示任何信息。
【解决方案3】:

MATLAB 的错误函数会自动显示文件名和行号。

function [ ] = wsgefiow9ey(  )
n = 7;
if n > 1
    msg = 'Error: n is too big.';
    error(msg)
end % if
end % function definition

click here to see console output resulting from call to MATLAB error function

【讨论】:

  • 谢谢!但是在屏幕上显示它是不够的。我想将它存储到一个变量中并将其打印为一个 excel 文件。我知道如何从 matlab 创建一个 excel 文件。我只是不知道如何将 m 文件的名称和行号存储到变量中。
猜你喜欢
  • 1970-01-01
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多