How to rewrite code without nested loops
2 views (last 30 days)
Show older comments
% Prompt for user input
r_values = input("Enter r: 0.0 to 4.0: ");
x1 = input("Enter initial x: 0.0 to 1.0: ");
N = 100;
% Iterations for uyser inputed r values
for r = r_values
x = zeros(1, N);
x(1) = x1;
%two x vales to get both plotted on same graph
x_prime = zeros(1, N);
x_prime(1) = x1 + 1e-9;
% Compute the logistic equation for both initial conditions
for n = 1:N-1
% For x1
x(n+1) = r * x(n) * (1 - x(n));
% For x1 + 1e-9
x_prime(n+1) = r * x_prime(n) * (1 - x_prime(n));
end
% Plotting both on the same graph
figure;
%Way to get both lines on same graph in specific way wanted
hold on;
plot(x, 'b-');
% Plot for x1 + 1e-9 in red
plot(x_prime, 'r-');
title(['Logistic Equation']);
legend('Initial x (red)', 'Initial x + 1e-9 (blue)');
grid on;
%Way to get both lines on same graph in specific way wanted
hold off;
end
0 Comments
Answers (2)
Voss
on 11 Apr 2024
% Prompt for user input
r = input("Enter r: 0.0 to 4.0: ");
x1 = input("Enter initial x: 0.0 to 1.0: ");
N = 100;
% number of user inputed r values
Nr = numel(r);
% two x values to get both plotted on same graph
x = zeros(Nr, N);
x(:,1) = x1;
x_prime = zeros(Nr, N);
x_prime(:,1) = x1 + 1e-9;
% Compute the logistic equation for both initial conditions
for n = 1:N-1
% For x1
x(:,n+1) = r(:) .* x(:,n) .* (1 - x(:,n));
% For x1 + 1e-9
x_prime(:,n+1) = r(:) .* x_prime(:,n) .* (1 - x_prime(:,n));
end
for ii = 1:Nr
% Plotting both on the same graph
figure;
%Way to get both lines on same graph in specific way wanted
hold on;
plot(x(ii,:), 'b-');
% Plot for x1 + 1e-9 in red
plot(x_prime(ii,:), 'r-');
title(['Logistic Equation']);
% legend('Initial x (red)', 'Initial x + 1e-9 (blue)');
legend('Initial x (blue)', 'Initial x + 1e-9 (red)');
grid on;
%Way to get both lines on same graph in specific way wanted
hold off;
end
0 Comments
George Abrahams
on 11 Apr 2024
This can be solved using a built-in MATLAB solver, ode45. However, the logistic equation actually has an analytic solution.
See Logistic Equation version 1: Super simple code to solve a first-order ODE and Logistic Equation version 2: Solve a first-order ODE for explanations of each.
More generally, to remove the loops you want to vectorize your code. This often increases code performance in MATLAB. As such, if you haven't already learned about array operations, I recommend that you read up on them.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!