Define a vector with random steps

I want to create an array with incremental random steps, I used this simple code.

t_inici=(0:10*rand:100);

The problem is that the random number remains unchanged between steps. Is there an easy way to change the seed of a random number at each step?

+6
source share
4 answers

If you have a set number of points , let's say nPtsyou can do the following

nPts = 10;         % Could use 'randi' here for random number of points
lims = [0, 10]     % Start and end points
x = rand(1, nPts); % Create random numbers  
% Sort and scale x to fit your limits and be ordered 
x = diff(lims) * ( sort(x) - min(x) ) / diff(minmax(x)) + lims(1) 

This approach always includes your endpoint, which is not suitable for the approach 0:dx:10.


If you had a certain number of points , let's say nPtsMaxyou can do the following

nPtsMax = 1000;      % Max number of points
lims = [0,10];       % Start and end points
% Could do 10* or any other multiplier as in your example in front of 'rand'
x = lims(1) + [0 cumsum(rand(1, nPtsMax))];     
x(x > lims(2)) = []; % remove values above maximum limit

, .

+5

N-2, N - , :

N=50;
endpoint=100;
initpoint=0;
randsamples=sort(rand(1, N-2)*(endpoint-initpoint)+initpoint);
t_inici=[initpoint randsamples endpoint];

, " ", "" 2 , . - ( ). , N . , ( , MATLAB ).

+3

" "

[initpoint,endpoint,coef]=deal(0,100,10);
t_inici(1)=initpoint;
while(t_inici(end)<endpoint)
  t_inici(end+1)=t_inici(end)+rand()*coef;
end
t_inici(end)=[];

, , 0, 100.

+3

, , . , , , .

. , , .

  • , n. , , , .
  • .
  • n () .
  • , .
  • If they are, cut as necessary and output the (final) result. Otherwise, back to step 3.

code:

lower_value = 0;
upper_value = 100;
step_scale = 10;
n = 5*(upper_value-lower_value)/step_scale*2; % STEP 1. The number 5 here is arbitrary.
% It probably more efficient to err with too many than with too few
result = lower_value; % STEP 2
done = false;
while ~done
    result = [result result(end)+cumsum(step_scale*rand(1,n))]; % STEP 3. Include
    % n new entries
    ind_final = find(result>upper_value,1)-1; % STEP 4. Index of first entry exceeding
    % upper_value, if any
    if ind_final % STEP 5. If non-empty, we're done
        result = result(1:ind_final-1);
        done = true;
    end
end
+2
source

All Articles