I have obviously done something wrong with the f function I just dont know what. I apologise as this is most likely extreamly basic.
% compute the expressions f(x) and g(x)for x=10^-1,10^-2,...,10^-14
% which values (f(x) or g(x)is more accurate
x=[10^-(1),10^-(2),10^-(3),10^-(4),10^-(5),10^-(6),10^-(7),10^-(8),10^-(9),10^-(10),10^-(11),10^-(12),10^-(13),10^-(14)];
f=(exp(2.*x)-(exp(x).*cos(x)).^2./x.^2)
f = 1×14
1.0e+28 * -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0001 -0.0100 -1.0000
g=(exp(x).*sin(x)./x).^2
g = 1×14
1.2173 1.0202 1.0020 1.0002 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
% modify program to compute relative error in the inaccurate values using
% the more accurate values as estimates of the true value. For each
% x=10^-1, 10^-2,...,10^-14, print x, computed values and relative error
error_f=(f(x)-g(x)/g(x))
Array indices must be positive integers or logical values.

댓글 수: 2

Since we're comparing f against g for some measure of accuracy, we need to know what they're supposed to be. The fact that they're vastly different means that one or both of the expressions is incorrect, but there's no way to know which.
There are a couple additional things that can't hurt:
x = 10.^-(1:14); % a simpler way to write that
f = (exp(2.*x)-(exp(x).*cos(x)).^2./x.^2)
g = (exp(x).*sin(x)./x).^2
error_f = (f-g)./g % f and g are just numeric vectors
I'm not sure that's the intended way to calculate the error, but that looks like what you were trying to do.
Tracy
Tracy 2021년 10월 3일
This is the original question

댓글을 달려면 로그인하십시오.

 채택된 답변

DGM
DGM 2021년 10월 3일

0 개 추천

There were some parentheses misplaced in the expression for f. That said, the error is still large, but I suppose that's intentional due to what the question is asking.
x = 10.^-(1:14); % a simpler way to write that
f = (exp(2*x) - (exp(x).*cos(x)).^2)./x.^2 % parentheses on numerator
g = (exp(x).*sin(x)./x).^2
error_f = (f-g)./g % f and g are just numeric vectors

추가 답변 (2개)

KSSV
KSSV 2021년 10월 3일

0 개 추천

Replace the line
rror_f=(f(x)-g(x)/g(x)) ;
with
rror_f=(f-g./g) ;
f and g are already evaluated with the given values of x.
When you use f(x), g(x) as f, g are arrays, you are trying to index them with x which is not correct.
Tracy
Tracy 2021년 10월 4일

0 개 추천

Thank you all so much for your help it is greatly appreciated.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

릴리스

R2021a

질문:

2021년 10월 3일

답변:

2021년 10월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by