function argument pow error
Mostra commenti meno recenti
not sure why I'm getting this error, any help will be appreciated. thanks
function topic4_p2_expand_then_bisect()
f = @(x) exp(-x) - x;
x0 = 0; d = 0.1; dmaxpow = 6;
% expand symmetrically until sign change or limit
found = false; pow = -1;
E = []; % expansion log [pow, a, b, f(a), f(b)]
end
while pow < dmaxpow
pow = pow + 1;
a = x0 - d; b = x0 + d;
fa = f(a); fb = f(b);
E(end+1,:) = [pow, a, b, fa, fb];
if fa*fb <= 0, found = true; break; end
d = 2*d;
end
write_csv('p2_expansion.csv', E);
if ~found, error('Failed to bracket a root.'); end
% bisection
tol = 1e-8; maxit = 100;
k=0; hist=zeros(maxit,5);
while k<maxit
k=k+1; m=0.5*(a+b); fm=f(m);
hist(k,:)=[k,a,b,m,fm];
if abs(fm)<tol || 0.5*(b-a)<tol, break; end
if f(a)*fm<0, b=m; else, a=m; end
end
hist=hist(1:k,:);
write_csv('p2_bisect.csv', hist);
% plot f on bracket
xs = linspace(a,b,400); ys = zeros(size(xs));
for i=1:length(xs), ys(i)=f(xs(i)); end
figure; plot(xs,ys,'-'); hold on; yline(0,'k--');
xlabel('x'); ylabel('f(x)'); title('f on final bracket'); grid on; hold off;
function write_csv(fname, M)
fid=fopen(fname,'w');
for i=1:size(M,1)
for j=1:size(M,2)
fprintf(fid,'% .16e',M(i,j));
if j<size(M,2), fprintf(fid,'');
end; fprintf(fid,'\n');
end; fclose(fid);
end
end
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Correlation and Convolution in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
