暂时在MATLAB中存储数字

时间:2014-09-11 10:34:15

标签: matlab

在MATLAB中将数字存储在内存中然后在for循环期间只将其中的特定子集写入矩阵/数组的最佳方法是什么?我也在努力为我的问题设置一个合适的for循环:

http://i.stack.imgur.com/yPAAn.png

我有一条特定长度的线(x = 100),以及特定位置的一条屏障(pos = 50)。我想进行多轮采样(在这种情况下,1000)并在每个采样中生成特定数量的随机数(p)。在所示的图像中,生成4个数字,我希望MATLAB在p> 1时采用最小的数字。当p

这可以在MATLAB中完成吗?我得到了:

x = 100;
sample = 1000; %number of rounds of sampling to do
pos = 50; %position of barrier 
nn = 1:12; %the number of random numbers to generate for each round of sampling i.e. 1000 rounds generating 1 number, 1000 rounds generating 2 numbers and so on
len1 = 0;
len2= x ;
for i = 1:sample
    p(i) = int16(rand()*x)
    if (p(i)<pos) && (p(i)>len1) 
        len(i) = p(i)
    end
end

我知道我需要第二句if语句

if (p(i)>pos) && (p(i)<len2)

我的想法是在使用默认的len1和len2值重新启动循环之前,暂时将len1和len2的值替换为每轮采样期间生成的最小和最大数字。可能有更好的方法。

非常感谢任何帮助,

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你应该做这样的事情

x = 100;       % length of the grid
pos = 50;      % position of the barrier
len1 = 0;      % left edge of the grid
len2 = x;      % right edge of the grid

sample = 1000; % number of samples to make
nn     = 1:12  % number of points to generate (will loop over these)

len = zeros(sample, length(nn)); % array to record the results

for n = 1:length(nn)                     % For each number of pts to generate
    numpts = nn(n);
    for i = 1:sample                     % For each round of sampling,
        p = round(rand(numpts,1) * x);   % generate 'numpts' random points.
        if any(p>pos)                    % If any are to the right of the barrier,
            pright = min(p(p>pos));      % pick the smallest.
        else
            pright = len2;
        end
        if any(p<pos)                    % If any are to the left of the barrier,
            pleft = max(p(p<pos));       % pick the largest.
        else
            pleft = len1;
        end
        len(i,n) = pright - pleft;       % Record the length of the interval.
    end
end

答案 1 :(得分:0)

这并不能解决您问题中的所有要点(临时存储数字的最佳方法),但会显示一种向量化方法,了解如何获得给定数字最接近(两侧)的两个数字有一个随机数列表。据我所知,这是你要求的部分内容。

n = 1000;         %// Number of random numbers
max_val = 100;    %// Max value
min_val = 0;      %// Min value
p = 50;           %// Border

x = rand(n,1)*(max_val-min_val)+min_val;  %// Vector of random numbers
s = sort([min_val; x; max_val]-p);        %// Sort vector, with border "shifted" to 0
ind = find(diff(sign(s)));        %// Find index of closest number smaller than p
res =  diff(s(ind:ind+1))    %// Difference between closest numbers on each side of p