필터 지우기
필터 지우기

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 CenterFile Exchange에서 Title에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by