2015-05-10 176 views
1

我有一個matlab問題需要解決。有兩個限制我的空間的向量,x_low和x_high。矩陣pos需要在這個空間內有值,矩陣的每一列都有兩個向量給出的不同邊界。現在我的問題是,蘭迪給兩個整數之間的值,但我需要改變每個列的界限。還有另一種方法來使用randi或不同的matlab函數來做到這一點? 我知道有更好的代碼要做到這一點,但我開始使用MATLAB和我知道做這樣一來,任何援助是值得歡迎的MATLAB函數替換randi生成矩陣

x_low = [Io_low, Iirr_low, Rp_low, Rs_low, n_low]; % vector of constant values 
x_high = [Io_high, Iirr_high, Rp_high, Rs_high, n_high]; % vector of constant values 
pos = rand(particles, var); 
var = length(x_high); 
for i = 1: particles  % rows             
    for k = 1: var   %columns          
    if pos(i, k) < x_low(k) || pos(i, k) > x_high(k) % if the position is out of bounder  
     pos(i, k) = randi(x_low(k), x_high(k), 1); % fill it with a particle whithin the bounderies  
    end 
    end 
end 
+0

你能提供樣本輸入/輸出嗎? – brodoll

回答

0

如果正確地明白,需要生成與整數值的矩陣,使得每個列具有不同的上限和下限;這些下限和上限是包括在內的。

這可以非常簡單地進行與

  • rand
  • bsxfun(照顧的列的基礎上的下限和上限),以及(0和1之間產生隨機數)
  • round(所以結果是整數值)。

讓輸入數據被定義爲

x_low = [1 6 11]; %// lower limits 
x_high = [3 10 100]; %// upper limits 
n_rows = 7;   %// number of columns 

然後:

r = rand(n_rows, numel(x_low));    %// random numbers between 0 and 1 
r = floor(bsxfun(@times, r, x_high-x_low+1)); %// adjust span and round to integers 
r = bsxfun(@plus, r, x_low);     %// adjust lower limit 

給出類似

r = 
    2  7 83 
    3  6 93 
    2  6 22 
    3 10 85 
    3  7 96 
    1 10 90 
    2  8 57 

如果您需要填寫值僅在矩陣pos的具體條目,你可以使用像

ind = bsxfun(@lt, pos, x_low) | bsxfun(@gt, pos, x_high); %// index of values to replace 
pos(ind) = r(ind); 

這有點矯枉過正,因爲只有產生於使用它的一些條目的整個matrixd r。要僅生成所需的值,最好的方法可能是使用循環。

+0

謝謝,這段代碼對我來說非常有用 – Andy

+0

@安迪我很高興聽到這個消息。 'bsxfun'是一個非常強大的功能。事實上,你發現這比'cellfun'更具可讀性說了很多關於你的Matlab技能​​:-) –

+0

是一個很好的方式來說我在Matlab上真的很糟糕? :D – Andy

0

您可以使用cellfun這一點。類似:

x_low = [Io_low, Iirr_low, Rp_low, Rs_low, n_low]; 
x_high = [Io_high, Iirr_high, Rp_high, Rs_high, n_high]; 

pos = cell2mat(cellfun(@randi, mat2cell([x_low' x_high'], ones(numel(x_low),1), 1), repmat({[particles 1]}, [numel(x_low) 1)])))'; 

最佳,

+0

謝謝,但我選擇了更易讀的第二個答案。 – Andy