In an assignment A(I) = B, the number of elements in B and I must be the same.
1 view (last 30 days)
Show older comments
I am working on this problem x(i+1)=rx(1-x) where the question says plot x as a function of r for 1<r<4.
Here is what I did:
r=1:0.01:4;
x=[];
x=0.35;
N=100;
for i=1:N;
x(i+1)=r*x(i)*(1-x(i));
end
but then this error message comes up. What's wrong with this code? How can I improve it?
0 Comments
Accepted Answer
Roger Stafford
on 19 Mar 2014
Edited: Roger Stafford
on 19 Mar 2014
Based on your description, presumably what you are requested to plot is the value of r along one axis and the corresponding value of x, starting with 0.35, after 100 repetitions of the given iteration along the other axis. To accomplish this you will need two for-loops, one nested inside the other. The single for-loop code you wrote does not work. It should be something like this:
r = 1:.01:4;
X = zeros(1,length(r));
for k = 1:length(r)
x = 0.35;
for c = 1:100
x = r(k)*x*(1-x);
end
X(k) = x; % You only need to store the last x value for each r(k)
end
plot(r,X,'y.')
Don't be discouraged by the strange appearance of the plot you get. There will be a certain degree of apparent chaos to it. That is inherent in the nature of the iteration formula.
EDIT:
Actually you don't have to use two nested for-loops. You can write it like this:
r = 1:.01:4;
x = repmat(0.35,1,length(r));
for k = 1:100
x = r.*x.*(1-x);
end
plot(r,x,'y.')
More Answers (1)
Walter Roberson
on 19 Mar 2014
x(i+1) can hold one element.
x(i) and (1-x(i)) are each one element, so x(i)*(1-x(i)) is one element.
r is 1:0.01:4 which is multiple elements. multiple elements multiplied by one element gives multiple elements. So the right hand side of the assignment has multiple elements and you are trying to save that into a single element.
Hint: you can make x into a two dimensional array and operate on rows at a time.
0 Comments
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!