print variable-name in Matlab

狂风中的少年 提交于 2019-11-27 09:14:24

Matlab essentially does not let you do that. However, you can write a helper function to ease your pain in creating output like that:

function disp_msg_var(msg, v)
  disp([msg inputname(2)]);
end

which you could call like so in your case:

disp_msg_var('Error in: ', a);

You can read more discussion on the topic on the Mathworks forum

Additionally, to list all current variables with values you can use the who function, but that is not the problem you presented.

varname=@(x) inputname(1);
disp(['Error in var: ' varname(mat)])

I'm adding another solution to the mix (one-liner):

function myFunction()
    mat = [1 2; 3 4];
    disp(['Error in var: ' feval(@(x)inputname(1),mat)])
end

Which outputs:

Error in var: mat

If you want to print out the variables present in a function, you can use the function WHO. Here's an example using a simple function test.m:

function test
  a = 1;
  b = 2;
  varNames = who();
  disp(sprintf('%s ','Variables are:',varNames{:}));
  c = 3;
  d = 4;
  varNames = who();
  disp(sprintf('%s ','Variables are:',varNames{:}));
end

Running this will give you the following output:

>> test
Variables are: a b 
Variables are: a b c d varNames
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!