Applying a constant function on a vector
조회 수: 5 (최근 30일)
이전 댓글 표시
Hi,
I am writing a program for school. I need the user to input a function as a string, and then I need to process it.
What I am doing:
f = vectorize(inline(user_input_string));
x = linspace(0, 20, 20);
y = f(x);
...
This works perfectly except when the user inputs a constant function (such as f = 1). In order for my project to work, y must be a vector. But if the user inputs a constant function, Matlab automatically sets y to a sclalar, instead of a vector.
What can I do?
댓글 수: 0
답변 (5개)
Star Strider
2012년 11월 22일
편집: Star Strider
2012년 11월 22일
I'm not certain I completely understand your problem. However, you could test for a scalar and if something like f=1 was the input, perhaps set y to:
f = '1';
y = polyval(str2num(f), x);
If the test for a scalar was true, you could also consider something like:
user_input_string = sprintf('polyval(%s, x)', f);
Without knowing more, that's the best solution I can come up with.
댓글 수: 2
Star Strider
2012년 11월 22일
If the user inputs a constant, what output for user_input_string do you want?
The polyval function outputs a vector of constant values equal to the scalar input value with a length equal to the length of your x-vector. It's the only option I can think of that's compatible with your user_input_string variable.
The version I posted earlier assumes the scalar is read in as a string. If you read f in as a numeric value instead, replace the %s with %f:
user_input_string = sprintf('polyval(%f, x)', f);
Matt Fig
2012년 11월 23일
You can specify the variable in your call to INLINE. For example, this works even if the user enters 2:
f = vectorize(inline(input('Enter a func of x : ','s'),'x'));
댓글 수: 2
Matt Fig
2012년 11월 23일
Ah, good catch...
I guess we could get fancy.
S = input('Enter a func of x : ','s');
f = vectorize(inline([S,'+zeros(size(x),class(x))'],'x'));
But, yuck.
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!