Add to a vector from loop

1 view (last 30 days)
Matt Baron
Matt Baron on 6 Mar 2021
Commented: Matt Baron on 27 Mar 2021
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 Comments
Matt Baron
Matt Baron on 6 Mar 2021
Ok, thank you. I will take a look! I appreciate your time.
Matt Baron
Matt Baron on 27 Mar 2021
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

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 6 Mar 2021
Edited: Stephen23 on 6 Mar 2021
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!