Function won't accept vector
5 次查看(过去 30 天)
显示 更早的评论
function result = g(x)
result= (2*x*exp(cos(6*x))*exp(-x)) + 15
" Error using * Inner matrix dimensions must agree."
I tried inputting g([0 1 2]), but I get this error. Can someone help me understand why? I would like the function to accept scalars and vectors.
I know there's such a thing as ".*", but when I created this function: (13/400)*(x.^3 - 30.876*x.^2 + 32.454*x + 99.89), it accepted [0 1 2] just fine.
0 个评论
回答(2 个)
KSSV
2018-2-23
编辑:KSSV
2018-2-23
g = @(x) (2*x.*exp(cos(6*x)).*exp(-x)) + 15 ;
result = g([0 1 2])
When you input a vector, you need to do element by element multiplication. This is done by using .*. Please read about matlab element by element operations. https://in.mathworks.com/help/fixedpoint/ref/times.html
3 个评论
James Tursa
2018-2-23
@Rachel: scalar*array gives the same result as scalar.*array, so in this particular case the * and the .* do the same thing. So in your 2nd function:
(13/400)*(x.^3 - 30.876*x.^2 + 32.454*x + 99.89)
The only multiply operations that you have involve a scalar (the (13/400) and the 30.876 and the 32.454 are all scalars). Hence there was no need in this particular case to use the .* operator.
In your 1st function, x and exp(cos(6*x)) and exp(-x) are all vectors that you are multiplying by each other so you must use the .* operator to get the element-wise multiplication that you want.
Shrirang
2018-2-23
I just tried it..Your function behaves perfectly fine with ".*" operator Here is an example.
function result = Test(x)
result= (2 .* x .* exp(cos(6 .* x)) .* exp(- x)) + 15;
and answer was ==> 15.0000 16.9219 16.2588
May be there was typo mistake in your trial In your second example you have properly handled the dot operator before ^ so there was no error.
Let me know if it works for you.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!