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

Time:12-07

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 40.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.

CodePudding user response:

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. E.g.,

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, e.g. x(1) and x(k) and x(k-1).

  • Related