How to insert numbers into a empty vector in a loop

Hello,
I have a function and I want to insert sqra(5,5) that i I will get results of x and counter.
How to put all these results into a empty vector by loop ,so x=[] and counter=[] , because then I will have to create a graph.
Thanks for the helpers :)
function fOut = f(xIn,mIn,sIn)
fOut = (exp(-0.5*((xIn-mIn)/sIn)^2)/(sIn*(2*pi)^0.5));
function xOut = sqra(mIn,sIn)
format short %fixed-decimal format with a total of 4 digits
epsilon = 1e-4;
flag = 0; %That use when condition need to stop for the "while" loop.
counter = 0; %counts the number of iterations. Is used to prevent infinite loops.
x=0.5 ; %Initial guess
while flag == 0
%Check for infinite loop
counter = counter + 1
if counter > 10000
error('Too many iterations');
end
x=x+(x-mIn)/((sIn)^2) %Calculating a formula Newton–Raphson method
if abs((exp(-0.5*((x-mIn)/sIn)^2)/((sIn)*sqrt(2*pi)))) < epsilon %Checking whether the function is close to zero.
flag = 1; %If yes, flag is raised and the while loop stops.
end
end
xOut = x;

回答 (2 件)

Rik
Rik 2020 年 11 月 18 日

1 投票

You should not put it in an empty vector. You should put the results in an array:
[m,s]=ndgrid(1:5);
xOut=zeros(size(m));
counts=zeros(size(m));
for n=1:numel(m)
[xOut(n),counts(n)]=sqra(m(n),s(n));
end
function [xOut,counter] = sqra(mIn,sIn)
epsilon = 1e-4;
flag = 0; %That use when condition need to stop for the "while" loop.
counter = 0; %counts the number of iterations. Is used to prevent infinite loops.
x=0.5 ; %Initial guess
while flag == 0
%Check for infinite loop
counter = counter + 1;
if counter > 10000
error('Too many iterations');
end
x=x+(x-mIn)/((sIn)^2); %Calculating a formula Newton–Raphson method
if abs((exp(-0.5*((x-mIn)/sIn)^2)/((sIn)*sqrt(2*pi)))) < epsilon %Checking whether the function is close to zero.
flag = 1; %If yes, flag is raised and the while loop stops.
end
end
xOut = x;
end

2 件のコメント

Emilia
Emilia 2020 年 11 月 18 日
There is a problem with the function how to fix it.
Rik
Rik 2020 年 11 月 18 日
Isn't the error message clear? The function and the file have the same name. Change one of them, or put the script part in a separate file.

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

Setsuna Yuuki.
Setsuna Yuuki. 2020 年 11 月 18 日
編集済み: Setsuna Yuuki. 2020 年 11 月 18 日

0 投票

You can try:
function [x0ut,count] = sqra(mIn,sIn)
while
counter=counter+1;
count(counter)=counter;
x(counter) = x+...
end
x0ut=x;
end
In main function:
[x0ut,count]=sqra(val1,val2)

1 件のコメント

Emilia
Emilia 2020 年 11 月 18 日
Did not work for me there is an error.

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

カテゴリ

ヘルプ センター および File ExchangeNetworks についてさらに検索

タグ

質問済み:

2020 年 11 月 18 日

コメント済み:

Rik
2020 年 11 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by