フィルターのクリア

Automatic legend changing based on the function

3 ビュー (過去 30 日間)
Agnieszka Polak
Agnieszka Polak 2019 年 12 月 20 日
コメント済み: Jack edwards 2019 年 12 月 20 日
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
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
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
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));
Jack edwards
Jack edwards 2019 年 12 月 20 日
Thats exactly what I needed, Thank you very much!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeTitle についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by