print variable-name in Matlab

2019-01-09 12:25发布

I have a function in Matlab that has some variables in it. I need to print out the variable_names (in case of an exception etc.). I am aware of inputname function but it works for input_arguments only.

mat = [ 1 2 ; 3 4 ] ;

% disp(['Error in var: ' ??(a)])
% desired ouput: Error in var: mat     (and NOT 1 2 ; 3 4!)

Thanks!

4条回答
ゆ 、 Hurt°
2楼-- · 2019-01-09 12:55

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
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-09 12:59
varname=@(x) inputname(1);
disp(['Error in var: ' varname(mat)])
查看更多
孤傲高冷的网名
4楼-- · 2019-01-09 13:03

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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-09 13:08

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
查看更多
登录 后发表回答