Why am I unable to pass a vector as an input to an inline object within MATLAB?
14 次查看(过去 30 天)
显示 更早的评论
Why am I unable to pass a vector as an input to an inline object within MATLAB?
I am trying to create an inline object that will take a vector as inputs, and use the elements of the vector as variables in the equation. For example,
f = inline('[2*sin(x) tan(x)*cos(y)]', '[x y]')
However, when I try to pass a vector as input to the object, I receive an error:
f([pi/2 pi/2])
??? Error: Only functions can return multiple values.
How can I pass a single variable as an input to the inline object?
采纳的回答
MathWorks Support Team
2009-6-27
This error occurs because of the way that the inline objects are created. The inline object contains strings that are evaluated using the EVAL function to determine the function value. In the example,
f = inline('[2*sin(x) tan(x)*cos(y)]', '[x y]')
the string is:
'[x y] = INLINE_INPUTS_{1};'
"INLINE_INPUTS" will be a cell array (similar to VARARGIN), where each cell element will contain one of the inputs to the inline object. However, MATLAB cannot return multiple object from indexing into an array with a single value, which is why the error occurs.
Instead, the inline object should be defined so that it uses a single variable, and that variable contains multiple elements:
f = inline('[2*sin(x(1)) tan(x(1))*cos(x(2))]', 'x')
Now, when the inline object is passed a single input variable, it will index into that variable to obtain the values.
In addition, if you have a function of a single variable, but you want to use a vector or matrix of values for that variable, you should use the VECTORIZE command on the inline function.
f = inline('x^2 + x + 1');
f = vectorize(f);
f([1 2;3 4])
which results in
ans =
3 7
13 21
0 个评论
更多回答(0 个)
另请参阅
类别
在 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!