Add to a vector from loop

6 次查看(过去 30 天)
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