MATLAB Answers

Creating a fourth column of my code

28 ビュー (過去 30 日間)
Hmm!
Hmm! 2021 年 1 月 16 日
I have the following codes:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
format longg
f= @(x) sin(x);
x0 = 2;
ref = cos(2);
hs = 10.^(-(1:16));
errors = [];
for h = hs
derivative = (f(x0+h) - f(x0-h))/(2*h);
error = abs(ref - derivative);
rate = [error(1); error(2:end)./error(1:end-1)];
errors = [errors error] ;
disp([h derivative error rate])
end
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The bolded line is a fouth column in disp([ . ]) which is supposed to be the entries by dividing two consecutive error respectively i,e., the entries in the third column of disp([ . ]). But what I have is rather the repetition of the third column as the fourth column which I dont want. The more I try fixing it, the more difficulties I face. I really need help which is that the fourth column of disp([ . ]) must be the consecutitive division of entries of the third column. Note that the first entry of the fourth column will be empty, 0 or -, because, there is no entry before the fisrt entry of column three. Thanks in advance!

  3 件のコメント

Athrey Ranjith Krishnanunni
Athrey Ranjith Krishnanunni 2021 年 1 月 16 日
ref and x0 are scalar, and f produces a scalar when its input is a scalar.
Inside the for loop, h is a scalar, hence derivative is scalar as well. Thus, error becomes a scalar, which means that the line
rate = [error(1); error(2:end)./error(1:end-1)];
just evaluates to
rate = error;
and causes the behaviour you see.
There are too many things going wrong here to give you the fix with minimum changes, but this would probably give you what you need:
errors = [];
derivatives = [];
for h = hs
derivative = (f(x0+h) - f(x0-h))/(2*h);
derivatives = [derivatives; derivative];
err = abs(ref - derivative); % try not to shadow the default error()
errors = [errors; err];
end
rate = [errors(1); errors(2:end)./errors(1:end-1)];
disp([hs', derivatives, errors, rate])
Hmm!
Hmm! 2021 年 1 月 16 日
ARK thanks. Could you explain why I shouldn't have used the default error() ?
Athrey Ranjith Krishnanunni
Athrey Ranjith Krishnanunni 2021 年 1 月 16 日
See this thread:
Your problems weren't caused by that, though. It's just good practice not to shadow native MATLAB functions.

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

回答 (0 件)

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by