Saving for loop output ever iteration

1 view (last 30 days)
I would like to save the output from the second for loop every iteration so that I can plot it vs the variable G at the end. I can't figure out the problem. The code:
% Chaos Theory - Mapping Chaotic Behavior
clc
clear all
n = 0;
size = 100; % Size of chaotic array
x = 0.5; % Initial value
xnew = zeros(101,size-1); %Initializes Array
for j = 1:101
G = 2.9 + n;
for i = 1:size-1
x(i+1) = G*x(i)*(1-x(i)); % Mapping Equation
end
xnew(i) = x;
n = n + 0.01;
% Use if animated plot is desired. Slows down simulation time.
% figure(1)
% hold on
% plot(G,x,'r.')
end
figure(1)
hold on
plot(G,xnew,'r.')

Accepted Answer

Cris LaPierre
Cris LaPierre on 18 Jan 2019
Edited: Cris LaPierre on 18 Jan 2019
There are some issues:
  1. you are not capturing/saving every value of G. You probably want to use loop counter j. G(j) = 2.9+n;
  2. You are saving x using loop counter i. I think you want to use loop counter j.
  3. When plotting, MATLAB treats columns as series, not rows. If you want to plot G vs x, you need your series data to be in columns (assign x to a column in xnew, not a row). Same goes for G - series value goes in corresponding column. Also means swapping your preallocation dimensions - zeros(size-1,101).
  4. The output of the second for loop is a vector. You are getting an error on the assignment because of that. Your preallocation of xnew suggests you need to specify what rows and column to assign x to: xnew(:,j) = x;
  5. There is a mismatch between what the size of x is, and what the size of xnew is. You likely don't want to include the initial value for x, so when allocating to xnew, use xnew(:,j) = x(2:end)
Try this:
% Chaos Theory - Mapping Chaotic Behavior
n = 0;
size = 100; % Size of chaotic array
x = 0.5; % Initial value
xnew = zeros(size-1,101); %Initializes Array
for j = 1:101
G(j) = 2.9+n;
for i = 1:size-1
x(i+1) = G(j)*x(i)*(1-x(i)); % Mapping Equation
end
xnew(:,j) = x(2:end);
n = n + 0.01;
end
plot(G,xnew,'r.')
I get this figure:

More Answers (0)

Community Treasure Hunt

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

Start Hunting!