Home > front end >  Use variable name for diagram title
Use variable name for diagram title

Time:05-03

How to use the variable name as a string for the title of the diagram in MATLAB

y = [11 22 33 44 55];

x = [1 2 3 4 5];

figure
plot (x,y)
title ('Diagram of ' x 'versus ' y);   % How to make this line work

The title should then read:

Diagram of x versus y

CodePudding user response:

You can write a helper function and use the inputname function

function tplot( varargin )
    plot(varargin{:})
    xname = inputname(1);
    yname = inputname(2);
    title( sprintf( 'Diagram of %s versus %s', xname, yname ) );
end

By using varargin, all normal functionality of plot will hold. However, this function assumes that the first two arguments are always the x and y data, which isn't strictly always the case for the normal plot function - to be handled as an edge case if required.

This can then be called using

y = [11 22 33 44 55];
x = [1 2 3 4 5];
figure
tplot(x,y); % titled plot

plot

CodePudding user response:

I dont know if I got your question correctly, but if the variable names always are x and y, just use one looong string:

('Diagram of  x versus  y')
  • Related