MATLAB: How to get the name of a MATLAB variable as a string

MATLAB

I would like to convert the name of my MATLAB variable to a string so that, for example, I can plot a variable and then use the name of the variable as a title for the plot. Is there a way to do this without having to store the name of the variable along with the data?

Best Answer

There is no direct way to get the name of a variable as a string, but there is a function called "inputname" that will return the name of a variable that was input into a function:
Using this, you can create a short function that, given a variable, will output the name of it as a string, as in the following example:
 
function out = getVarName(var)
out = inputname(1);
end
As long as the file is included on the MATLAB path, you can use the function in the following way:
 
>> x = 1:10; % example data
>> plot(x)
>> title(getVarName(x))