I have a problem with integration "Error using / Matrix dimensions must agree"

syntax is here:
clc;clear all;close all;
m=input('input a value');
x=linspace(1,2,m);
%function
f=(x+(1/x)).^2;
%real value of integral
ff=@(x)(x+(1/x)).^2;
RV=integral(ff,1,2);
%Solution with numerical method (Trap method)
IT=Trap(x,f,m)
ybh=100*(abs(RV-IT)/RV
function IT=Trap(x,f,m)
IT=(x(m)-x(1))*(f(1)+f(m))/2
return
end
Why this isnt working?
ERROR:
input a value2
Error using /
Matrix dimensions must agree.
Error in odev (line 5)
f=(x+(1/x)).^2;
Thank you.

 採用された回答

Fabio Freschi
Fabio Freschi 2019 年 11 月 6 日
When you define your functions use ./ instead of /
%function
f=(x+(1./x)).^2;
%real value of integral
ff=@(x)(x+(1./x)).^2;

6 件のコメント

Filious
Filious 2019 年 11 月 6 日
I already tried that I still got same error
Fabio Freschi
Fabio Freschi 2019 年 11 月 7 日
I don't see any error with my correction. I can't check all the code because you didn't share your Trap function. If you can attach it, I can try to check it out
Jan
Jan 2019 年 11 月 7 日
@Filious: Then please post the current version of your code an a copy of the complete error message.
I did not check the correctness of the results, but the code runs without problems, e.g. no errors, when you change the functiond definitions as I said
%function
f=(x+(1./x)).^2;
%real value of integral
ff=@(x)(x+(1./x)).^2;
And you close the bracket in the last line
ybh=100*(abs(RV-IT))/RV
Maybe I got the point: your code does not exit with an error, but it produces the wrong result!
Your implementation of the trapezoidal rule is not correct. You are not using all your samples but only the first and last points. If you really don't want to use the built-in trapz, you can implement yourself as
Itrap = sum((f(2:end)+f(1:end-1)).*(x(2:end)-x(1:end-1))/2)
Filious
Filious 2019 年 11 月 7 日
Thank you. You were very helpful. It turns out I didnt try your correction exacly

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

その他の回答 (0 件)

カテゴリ

製品

質問済み:

2019 年 11 月 6 日

コメント済み:

2019 年 11 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by