Add to a vector from loop

조회 수: 1 (최근 30일)
Matt Baron
Matt Baron 2021년 3월 6일
댓글: Matt Baron 2021년 3월 27일
Team,
Just learning how to use MatLab here,
How do I insert the value n into a different variable so I can recall each number? Any other advice is much appreciated. I just started MATH240 so will need more help later ;)
-----------------------------------------------
totaln=0;
n=1;
for n=1:1000000;
if abs(cos(n))<1/n;
totaln=totaln+1;
display(n) %this displays n but then updates it with the next iteration, I want to insert the value of n into a vector so I can see recall them later.
n=n+1;
else;
n=n+1;
end;
end;
  댓글 수: 5
Matt Baron
Matt Baron 2021년 3월 6일
Ok, thank you. I will take a look! I appreciate your time.
Matt Baron
Matt Baron 2021년 3월 27일
Mr. Cobeldick,
Just wanted to share with you how far I have come since this question with you and others' help;
syms e imp r
A=zeros([],2);%create an empty 0 by 2 matrix for later
display("Hello! Welcome to Matt Baron's numerical solver. Press enter to continue.")
pause
step = input('What step size would you like?');
initcondx = input('What is the initial condition for x?');
initcondy = input('What is the initial condition for y?');
n=1;%start at 1
x=initcondx;%start at the initial condition
y=initcondy;%start at the initial condition
dfeq=input('What differential equation do you want approximated? i.e. .2 * x * y','s');
f=str2func(sprintf('@(x,y)%s',dfeq));%the function to be evaluated
est=input('What value do you want the equation estimated to?');
%actual=@(x) (exp(.1 .* (x .^2) - .1));%the solved function
choice = input('Press e for Euler, imp for Improved Euler, or r for RK4.');
if choice == e
while x <= est%what value do you want it estimated to
A(n,:)=[x,y];
y = (A(n,2) + ((step) * f(A(n,1),A(n,2))));
x = (initcondx) + ((n) * (step));
%abs = actual(x) - y;
%rel = (abs / actual(x)) * 100;
n=n+1;
end
else
if choice == imp
while x <= est
A(n,:)=[x,y];
A(n+1,2) = y + ((step) * f(A(n,1),A(n,2)));
A(n+1,1) = (initcondx) + ((n) * (step));
y = A(n,2) + ((step) * ((f(A(n,1),A(n,2)))+f(A(n+1,1),A(n+1,2))))/(2);
x = (initcondx) + ((n) * (step));
n=n+1;
end
A(n,:)=[];
end
end
A

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2021년 3월 6일
편집: Stephen23 2021년 3월 6일
The MATLAB way:
N = 1:1000000;
X = abs(cos(N)) < 1./N;
T = nnz(X) % total
T = 7
Z = N(X) % those which pass your condition
Z = 1×7
1 2 11 33 52174 260515 573204

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by