【问题标题】:switching numbers in matlab [closed]在matlab中切换数字[关闭]
【发布时间】:2014-05-13 16:19:08
【问题描述】:

我有 N 个时间步,想创建 N 个与每个时间步相对应的实数,如下所示:这些数字应在 [a, b] 范围内,切换概率为 p。 即,如果第k个数(对应于第k个时间步)是n,那么第k+1个数(对应于k+1个时间步)是任何不同于n的数的概率是p。所有创建的数字都应在 [a,b] 范围内。

如何在 matlab 中做到这一点? 谢谢。

【问题讨论】:

  • 诚然,我是在推测,但是,如果您对模拟有限马尔可夫链感兴趣,那么您提出问题的方式会让人们感到困惑。
  • 没有。我的目标和上面提到的一样。
  • @user3489173 问题不是很清楚,请编辑
  • What have you tried?您的问题是在[a, b] 中生成随机数还是在给定数字k 中生成数字k+1
  • @user3489173:在 Stack Overflow 上发布一个问题,而不是首先付出一些努力,这是不受欢迎的。请自己尝试一下,然后在遇到困难时发布问题。

标签: matlab random


【解决方案1】:

保证超级随机:

N = randi(100);
p = rand;
l1 = rand*randi(100);
l2 = rand*randi(100);

if l2 < l1
  [l2 l1] = deal(l1,l2);
end

out = []

while isempty(out)
    if rand>rand
        n = 2:N
        a = rand([N,1])*(l2-l1)+l1;
        x = rand([N-1,1])<p;
        n(x==0)=n(x==0)-1;
        n = [1 n];
        out = a(n);
    end
end

【讨论】:

    【解决方案2】:

    我不确定我是否满足您的所有要求,但这可能是您正在搜索的脚本:

    N = 10;     % count of numbers
    p = 0.2;    % switching probability
    a = 5;
    b = 20; 
    
    % init empty numbers and get the first random number
    numbers = zeros(N,1);
    numbers(1) = rand(1) * (b-a) + a;
    
    for iNumber = 2:N
        % test if number must change
        if rand(1) < (1-p)
            % the number must be the same than the previous
            % copy the value and go to next number
            numbers(iNumber) = numbers(iNumber-1);
            continue;
    
        else 
            % a new number must be found
            while 1
                % get a new random number 
                numbers(iNumber) = rand(1) * (b-a) + a;
    
                % check if the new random number is different from the previous
                if numbers(iNumber) ~= numbers(iNumber-1)
                    % in case they are different, the while 1 can be stopped
                    break;
                end
    
            end % while 1
    
        end % if rand(1) < (1-p)
    end % for iNumber = 2:N
    

    【讨论】:

    • 好像没问题。无数次感谢...
    猜你喜欢
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多