MATLAB Answers

How can I make a loop that gives values in each iteration?

23 views (last 30 days)
Kownain Al Hashmi
Kownain Al Hashmi on 24 Feb 2021
Edited: Kownain Al Hashmi on 24 Feb 2021
In my code, I can only get final values for Fe (forward error) and Be (backward error). How can I make a loop that gives me values for both errors in each iteration (line 20 to line 23 needs correction), there are total 7 iterations.
clear;
clc;
format long e;
%constants
m = 2000;
k = 500E3;
c = 38E3;
x_y = 0.2;
w = 0.1:0.01:100;
f = @(w)sqrt((m.*c.*w.^3)./(k.*(k-m.*w.^2)+(c.*w).^2))-(x_y);
options = optimset('tolX',2.2e-16);
[r] = fzero(f,[2 8],options); % exact value
options = optimset('display','iter','tolX',1e-10);
[xc] = fzero(f,[2 8],options);
for i = 1:length(w)
Fe(i) = abs(f(xc(i)));
Be(i) = abs(r-xc(i));
end
fprintf('\nxc = %f\t\n',xc);
disp('Forward error = ')
disp(Fe);
disp('Backward error = ')
disp(Be);

Answers (1)

Alan Stevens
Alan Stevens on 24 Feb 2021
Why do you need a loop? There is just one zero between 2 and 8. Your values of w are not used in any meaningful way (they would be if you were to plot f(w) vs w). You can just replace your loop with
Fe = abs(f(xc));
Be = abs(r-xc);
  1 Comment
Kownain Al Hashmi
Kownain Al Hashmi on 24 Feb 2021
I need loop so I can know how close I am to root in each step. I already did the above code and it giving me the final values only. If you know any way to put it in loop, please let me know. Thanks!

Sign in to comment.

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!