2013-08-28 34 views
-1

我必須將一個矢量傳遞給MATLAB中的函數。它有六個元素,每個元素可以取四個不同的值。我需要製作一個可以覆蓋所有可能組合的循環。如何實現一個循環來創建一組向量中的一組值的所有可能的組合?

基本上,載體應取的值:

0.4 0.4 0.4 0.4 0.4 0.4 

0.4 0.4 0.4 0.4 0.4 0.6 

0.4 0.4 0.4 0.4 0.4 0.8 

0.4 0.4 0.4 0.4 0.4 1.0 

0.4 0.4 0.4 0.4 0.6 0.4 

0.4 0.4 0.4 0.4 0.6 0.6 

... 

... 

1 1 1 1 1 1 

我認爲會4^6 = 4096的組合。我必須運行每個組合的功能。那麼我怎麼能在這裏做循環?我嘗試了幾個嵌套循環,我可以改變其中一個值並循環該值的位置,但這不會產生每個組合。請幫助?

另一個說明,將所有這些4096向量順序傳遞給一個函數會導致任何問題?像系統掛起? (我用i5,4 GB Ram)。

MATLAB的7.9.0(R2009b中)

+0

爲什麼不能做這一切的功能裏面?看看我的回答,只有兩行添加到函數中(如果你通過原始的vactor)。 – Adiel

回答

-1

您可以保存所有的循環:

data=0.4:0.2:1; 
DupData=kron(ones(1,6),data); 
DesResult=unique(nchoosek(DupData,6),'rows'); 

這會給你通過你想要的順序,沒有循環的載體......

1

好吧,如果你只需要編寫一個循環,一個辦法是:

for i = [0.4 0.6 0.8 1]; 
    for j = [0.4 0.6 0.8 1]; 

    % work 
    output = myfunction(whatever, args, i, j); 

    end 
end 

在循環中,i和j將採取值該數組(0.4,0.6,0.8,1)。如果你想你的迭代器變量採取整數值,以便你可以使用它們作爲你的輸出的索引,你可以做這樣的事情。

% out-of-loop variables 
combo = [0.4 0.6 0.8 1] 
output = zeros(length(combo)); % good coding practice to initialize variable outside of loop. 

for i = 1:length(combo); 
    for j = 1:length(combo); 

    % work 
    output(i,j) = myfunction(whatever, args, combo(i), combo(j)); 

    end 
end 

不,運行一個5000長的循環不會導致掛斷。

+0

謝謝。我使用了6個循環,並將每個循環變量用作數組元素。 – Analon

0

要生成本系列的index th元素,請將您的索引轉換爲基數爲4的數字。就像這樣:

values = 0.4:0.2:1; 
index = 2314; 
base4representation = dec2base(index, 4, 6); %Returns the string "210022" 
bese4representation_vector = double(base4representation-'0'); %Returns the vector [2 1 0 0 2 2] 
result = values(bese4representation_vector+1); %Returns [.8 .6 .4 .4 .8 .8]  

如果你願意,你可以放入這個循環生成所有4096倍的值(從0開始)。或者你可以隨時產生它們。

相關問題