MATLAB Answers

Automatic legend changing based on the function

3 views (last 30 days)
Hello!
I am trying to write a code in whoch the user can imput their own function. I want to create a suitable legend that reflects the inputted functions automatically.
How could I approach that?
Thank you!

  1 Comment

Guillaume
Guillaume on 20 Dec 2019
You need to provide a bit more explanation and perhaps an example for us to understand what you're asking.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 20 Dec 2019
First, minor things:
  • I would recommend you put a space (preceded by a colon maybe) at the end of your input strings so that what the user types is a bit separated from your prompt.
  • I would also modify the function prompts to say that the functions must be expressed in term of x.
So, something like:
f1 = input('Please input your first function of x: ');
As your code is currently designed, it never sees the actual function. I feel your variable names f1 and f2 are a bit misleading as f1 and f2 are not functions, they're the values of the functions evaluated at the values of x. input does this evaluation for you (which incidentally makes input a dangerous function. If the user enters a command to format the hard disk, input will happily do so).
So, if you want to capture the function that was entered, you would need to stop input evaluating the function and return what was typed instead. You can then do the evaluation yourself:
f1 = input('Please input your first function of x: ', 's'); %the 's' tells matlab to return what was entered as is, without evaluating it
%f1 is now the text that the user entered, so you can use that as legend
plot(x, eval(f1), 'c-', 'LineWidth', 2); %evaluating f1 the same way that input originally did
%... same for f2
%...
legend(f1, f2, 'location', 'bestoutside');
Note that I'm using eval to perform the same evaluation that input did. eval is a very dangerous function which typically encourages bad coding patterns and thus we strongly recommend against using it. In this particular context however it is the simplest way to achieve what you want without going into more advanced coding patterns.

  6 Comments

Show 3 older comments
Jack edwards
Jack edwards on 20 Dec 2019
Thank you for your quick response. How would this work for the title of a graph?
Guillaume
Guillaume on 20 Dec 2019
I'm not sure I understand your question. Text is text, you can use it for whatever you want, including figure title. e.g.
title(sprintf('Graph of function %s and %s', f1, f2));
Jack edwards
Jack edwards on 20 Dec 2019
Thats exactly what I needed, Thank you very much!!

Sign in to comment.

More Answers (0)

Sign in to answer this question.