How to rewrite code without nested loops

2 visualizaciones (últimos 30 días)
Bob Meyes
Bob Meyes el 11 de Abr. de 2024
Respondida: George Abrahams el 11 de Abr. de 2024
% 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

Respuestas (2)

Voss
Voss el 11 de Abr. de 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

George Abrahams
George Abrahams el 11 de Abr. de 2024
This can be solved using a built-in MATLAB solver, ode45. However, the logistic equation actually has an analytic solution.
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.

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by