loop in a loop

9 vues (au cours des 30 derniers jours)
Hugo B
Hugo B le 25 Fév 2022
Modifié(e) : Stephen23 le 25 Fév 2022
Hello!
I want to repeat the inner loop 10 times but it doesn't work. How do I solve that?
(Part of a bigger project)
hold on;
for k=1:10
for i=1:n-1
y(i+1)=y(i)+f(y(i))*dt+g(y(i)).*(B(i+1)-B(i));
end
plot(t,y)
end
  10 commentaires
Torsten
Torsten le 25 Fév 2022
B = sqrt(dt)*randn(n,1)
instead of
for i=2:n
b = b + sqrt(dt)*randn(1);
B = [B;b];
end
Otherwise, the B in the inner loop will still be unchanged.
Hugo B
Hugo B le 25 Fév 2022
Modifié(e) : Stephen23 le 25 Fév 2022
Answer in comment from Torsten works. Thank you everyone!

Connectez-vous pour commenter.

Réponses (2)

Torsten
Torsten le 25 Fév 2022
Modifié(e) : Torsten le 25 Fév 2022
The outer loop is superfluous - so I deleted it.
dt = ...;
B = ...;
f = @(y) ...;
g = @(y) ...;
t = ...;
y = zeros(size(t));
y(1) = ...;
for i = 2:numel(t)
y(i) = y(i-1) + f(y(i-1))*dt + g(y(i-1))*(B(i)-B(i-1));
end
plot(t,y)
  1 commentaire
Hugo B
Hugo B le 25 Fév 2022
I want the outer loop to be able to repeat the inner loop 10 times. Since Brownian motion is included in earlier steps, this loop will change every time, which I want and to be able to plot it.

Connectez-vous pour commenter.


Voss
Voss le 25 Fév 2022
figure();
n = 100;
t = linspace(0,1,n);
dt = t(2);
f = @some_function;
g = @some_function;
B = randn(1,100);
hold on;
for k=1:10
y = zeros(1,n); % (re-)initialize y to be all zeros for each plot
for i=1:n-1
y(i+1)=y(i)+f(y(i))*dt+g(y(i)).*(B(i+1)-B(i));
end
plot(t,y);
end
function out = some_function(in);
out = in+randn(size(in));
end
  1 commentaire
Hugo B
Hugo B le 25 Fév 2022
I think this could work but now the inital values does not work. How do I add this again? initial for y I mean

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by