필터 지우기
필터 지우기

Saving for loop output ever iteration

조회 수: 1 (최근 30일)
Kelly McGuire
Kelly McGuire 2019년 1월 18일
편집: Cris LaPierre 2019년 1월 18일
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.')

채택된 답변

Cris LaPierre
Cris LaPierre 2019년 1월 18일
편집: Cris LaPierre 2019년 1월 18일
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:
  댓글 수: 1
Kelly McGuire
Kelly McGuire 2019년 1월 18일
Excellent! I was missing G and xnew. Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by