Automatic legend changing based on the function
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Guillaume
2019-12-20
You need to provide a bit more explanation and perhaps an example for us to understand what you're asking.
采纳的回答
Guillaume
2019-12-20
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 个评论
Guillaume
2019-12-20
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));
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Title 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!