简体   繁体   中英

MATLAB: how do I create a vector where each element is a function of the previous element

Working in Matlab. I am trying to create a vector where each element is a function of the previous element. The goal is to put the first 50 (or so) values of a logistical function in a vector. So I start with 0.200, with r=4 (for example), the second element would then be 4 0.200 (1-0.200)=0.640. The third element would take the value 0.64 and perform the same function on that number, and so on... I have tried a for-loop, but since there is no counter in the function, the loop doesn't work.

EDIT: I have created the following function:

     n = 0;
        x = 0.200; 
        for n=0:100
            x=4*x*(1-x)
            n=n+1
        end

This gives the first 100 values. But I fail to get them as values in a vector...

Any suggestions on how to solve this would be appreciated.

You need to use indexing for the x vector you are creating. The way you currently have it coded, everything is going into a scalar x and not a vector x. Eg,

n = 50; % the number of elements you want to fill
x = zeros(1,n); % allocate a vector to hold the numbers
x(1) = 0.200; % set the first value
for k=2:n % loop through the remaining values 
    x(k) = 4*x(k-1)*(1-x(k-1)); % set the next value using the previous value
end

Note that in the above code all of the usages of x other than the initial allocation involve indexing, eg x(1) and x(k) and x(k-1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM