How to insert numbers into a empty vector in a loop
21 views (last 30 days)
Show older comments
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;
0 Comments
Answers (2)
Rik
on 18 Nov 2020
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 Comments
Rik
on 18 Nov 2020
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.
on 18 Nov 2020
Edited: Setsuna Yuuki.
on 18 Nov 2020
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)
See Also
Categories
Find more on Loops and Conditional Statements 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!