You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义含增量随机步长的向量?解决rand值固定及种子更改问题

Creating a Vector with Randomly Varying Step Sizes

Hey there! I get what you're trying to do—your current code t_inici=(0:10*rand:100); uses a single random value for the step size (since rand only runs once when the colon operator evaluates), so every step ends up being the same. Let's fix that with some straightforward approaches to get unique random steps every time until you hit 100.

Why Your Current Code Doesn't Work

Matlab's colon operator (start:step:end) calculates the step value once at the beginning, then repeats it for the entire sequence. That's why your random number stays fixed—10*rand is computed just once, not for each step.

Method 1: Build the Vector Step-by-Step with a Loop

This is the most intuitive approach: start at 0, keep adding a new random step until you reach (or exceed) 100, then adjust the last value to exactly 100 if needed.

t_inici = 0; % Start at 0
while t_inici(end) < 100
    next_step = 10 * rand; % Generate a new random step each time
    t_inici = [t_inici, t_inici(end) + next_step];
end
% Trim the last value to exactly 100 if it overshoots
t_inici(end) = 100;

Method 2: Use Cumulative Sums (Faster, No Loop)

If you prefer a vectorized approach (which is often faster in Matlab), generate a bunch of random steps first, compute their cumulative sum, then truncate the sequence to stop at 100.

% Generate more than enough random steps (100 is way more than needed here)
random_steps = 10 * rand(1, 100);
% Build the sequence starting at 0, adding cumulative steps
t_inici = [0, cumsum(random_steps)];
% Find the first index where the value exceeds 100
first_over = find(t_inici > 100, 1);
% Truncate the sequence and set the last value to exactly 100
t_inici = [t_inici(1:first_over-1), 100];

Bonus: Control Step Size Range

If you want to tweak the step size range (instead of 0 to 10), just adjust the rand call—for example, 5 + 5*rand would give steps between 5 and 10, or randi([2,15]) for integer steps between 2 and 15.

内容的提问来源于stack exchange,提问作者Joan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:26:25