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

1 回表示 (過去 30 日間)
regina
regina 2015 年 12 月 1 日
コメント済み: regina 2015 年 12 月 1 日
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))];
  1 件のコメント
regina
regina 2015 年 12 月 1 日
thank you so so much! this worked perfectly

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by