Error using plot Vectors must be the same length. Error in Untitled11 (line 40) plot([xn xn],[ymin ymax],'r-','Linewidth',2)
Show older comments
function bisection_method()
myfunc = input ('myfunc: ');
A(1) = input('A: ');
B(1) = input('B: ');
e(1) = input('error : ');
n = input('loop for n: ');
disp('***********************************************');
x = linspace(A,B,100);
y = myfunc(x);
fig = figure();
set (fig,'color','White')
plot(x,y)
grid on
hold on
ymax = max(y);
ymin = min(y);
plot([A A],[ymin ymax],'k-')
plot([B B],[ymin ymax],'k-')
I=0;
for i=1:n;
I=1+I;
C(i) = (A(i)+B(i))/2;
fprintf('%d)\t%f\t%f\t%f\t%f\n', I, A(i), B(i), C(i), e(i));
FC(i) = myfunc(C(i));
FB(i) = myfunc(B(i));
if(FC(i)*FB(i)>0)
B(i+1) = C(i) ;
A(i+1)=A(i);
else
A(i+1) = C(i) ;
B(i+1)=B(i);
end
e(i+1) = (abs((FB(i)-FC(i))/FB(i)))*100;
end
disp('**********************************************');
xn = B;
yn = myfunc(xn);
while abs(yn)>1e-8
xn = xn+C(i);
plot([xn xn],[ymin ymax],'r-','Linewidth',2)
pause
ystar = myfunc(xn);
if sign(ystar)~= sign(yn)
C(i) = -C(i);
end
yn = myfunc(xn);
C(i) = C(i)/2;
end
xn
yn
function out = myfunc(in)
out = myfunc ;
1 Comment
Brendan Hamm
on 3 Aug 2015
Please format this with the '{ } Code' button.
Answers (1)
Walter Roberson
on 3 Aug 2015
You have
x = linspace(A,B,100);
y = myfunc(x);
your myfunc returns its input, so your y is the same size as x, a vector of length 100. Then you have
ymax = max(y);
ymin = min(y);
so your ymin and ymax are each scalars that are the min and max of y respectively.
After that you have for i=1:n and inside that for loop you assign to B(i+1), so your B becomes a vector of length n+1. After the loop you have xn = B; and since your B is a vector of length n+1 your xn becomes a vector of length n+1 before the loop. Inside the loop you have
xn = xn+C(i);
plot([xn xn],[ymin ymax],'r-','Linewidth',2)
The first of those increments the entire vector xn by C(i), resulting in a vector the same length (that is, n+1). Then in the plot [xn xn] is going to be a vector of length 2*(n+1) . Your ymin and ymax are scalar so [ymin ymax] is a vector of length 2. You are trying to plot a vector of 2*(n+1) x values against 2 y values and that is going to fail unless the user entered 0 for n.
Categories
Find more on Line Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!