How to rewrite code without nested loops

조회 수: 2 (최근 30일)
Bob Meyes
Bob Meyes 2024년 4월 11일
답변: George Abrahams 2024년 4월 11일
% 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

답변 (2개)

Voss
Voss 2024년 4월 11일
% 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 2024년 4월 11일
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.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by