Function won't accept vector

5 ビュー (過去 30 日間)
Rachel Dawn
Rachel Dawn 2018 年 2 月 23 日
コメント済み: Rachel Dawn 2018 年 2 月 23 日
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.

回答 (2 件)

KSSV
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 件のコメント
Rachel Dawn
Rachel Dawn 2018 年 2 月 23 日
Thank you, James!

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


Shrirang
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.
  1 件のコメント
Rachel Dawn
Rachel Dawn 2018 年 2 月 23 日
Hello. Thank you for your response. I would like to know why is it that in my 2nd function, I use ".^" and in the first function I use ".*" ? Why does my 2nd function accept vectors without the use of ".*"?

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

Community Treasure Hunt

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

Start Hunting!

Translated by