Resizing pre-allocated vector of zeros using while and if terms?

1 次查看(过去 30 天)
Hi, i'm writing a function that starts off with two intial values x(1) and x(2), then does the secant iteration on this to give a vector (called res) with the left hand side being each value in-putted and the right hand side being f(x)
What i want to do now is as soon as NaN comes up as an answer for the left hand side, i want to stop adding any values to the vector and then finish the function (so in this case it would give a vector of 11 rows instead of 20). Also as soon as there is a repeat on the left i want to do the same, and have a vector each number only occurring once on the left hand side (so here the 1.49... number that repeats 3 times i'd only want the first time)
x=zeros(20,1);
x(1)=1;
x(2)=2;
for k=2:20;
x(k+1)= secant iteration formula
res=[x,f(x)];
if res(:,1)==0; %if number in the left hand column=0
x=zeros(k-1,1); %then resize vector of zeros to have length k-1
res=[x,f(x)]
end
res=[x,f(x)]
end
this doesn't work so far, i have been trying to tweak it for the whole day so any help would be appreciated, thanks!

采纳的回答

valdal
valdal 2015-12-1
You can try something like :
n = 100;
x = zeros(n,1);
x(1) = 1;
x(2) = 2;
for i = 2:n-1
x(i+1) = x(i) - f(x(i))* (x(i) - x(i-1)) / (f(x(i)) - f(x(i-1)));
if (x(i+1) == x(i))
break
end
end
res = [x(1:i) f(x(1:i))];

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by