How to insert numbers into a empty vector in a loop
21 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Rik
2020-11-18
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 个评论
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.
2020-11-18
编辑:Setsuna Yuuki.
2020-11-18
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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!