How to insert numbers into a empty vector in a loop
조회 수: 19 (최근 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!