2015-03-02 26 views
0

我必須做一個函數,需要3個輸入,如e0e1e2。該功能將有2個輸出xyMatlab - 生成輸入和他們的總和的組合

x將是e0,e1e2的組合。 y將是列向量,包含列的總和x

下列條件必須創建功能時,應該滿足:

  1. 輸入e0e1e2各自具有單個數字。
  2. 如果用戶未輸入值,則默認設置爲0。
  3. 如果用戶未輸入任何輸入,則應顯示未輸入輸入的消息。

下面是一個例子:

combination pattern of X (first 3 columns):  pattern for y is the sum of x 
1 1 1           3 
2 1 1           4 
3 1 1           5 
1 2 1           4 
2 2 1           5 
3 2 1           6 
1 3 1           5 
2 3 1           6 
and so on...       and so on.... 

到目前爲止,我只能夠做到這一點多少與xy單獨顯示。

function [x,y]=create(e0,e1,e2) 
switch nargin 
case 2 
    e1=0; 
    e2=0; 
case 1 
    e2=0; 
case 0 
    disp('no input') 
end 

我GOOGLE了我的問題,發現combvec和allcomb應該幫助,但我找不出如何.. 請幫助任何回答或暗示將會有很大的幫助。

回答

1

您和allcomb在正確的軌道上。你其實都是在尋找cartesian product

[e0, e1, e2] x [e0, e1, e2] x [e0, e1, e2] == [e0, e1, e2]^3. 

你不需要allcomb但是,作爲ndgrid可以already do this

讓我們從您的代碼開始。它有一個錯誤。基本上case 2case 1翻轉。

function [x,y] = create(e0,e1,e2) 
switch nargin 
case 2 
    e1=0; % <- When nargin==2, this value is set, and you overwrite it. 
    e2=0; 
case 1 
    e2=0; % <- When nargin==1, e1 must also be set to zero. 
case 0 
    disp('no input') % <- use `error` instead of `disp`? If not, use `return` here. 
end 

然後您需要檢查提供的數字不是矩陣。這可以通過類似的東西來實現。 (填空)。

assert(numel(e1)==1 && numel(__)___ && numel(__)___,'Input sizes are incorrect'); 

要生成[e0, e1, e2] x [e0, e1, e2] x [e0, e1, e2]您正在尋找笛卡爾乘積,您可以使用this answerallcombthis answer爲內置ndgrid

sets = {[e0,e1,e2], [e0,e1,e2], [e0,e1,e2]}; 

cartProd1 = allcomb(sets{:}) 

[x y z] = ndgrid(sets{:}); 
cartProd2 = [x(:) y(:) z(:)] 

如果您需要正確的排序,您可以交換cartProd的列。 要生成沿行的總和,請使用

sum(cartProd,2) 
+0

非常感謝。你的回答幫了我很多。現在我清楚地明白我做錯了什麼。 – 2015-03-04 10:02:03

+0

@Frankwiene:我的榮幸! – knedlsepp 2015-03-04 10:05:12

0

你想要的是排列不是組合。您列出2 3 13 2 1是不同的,但如果您要將其組合,則可以認爲這些組合是相同的。因此,我要請您看看這篇文章,而不是:

How to find all permutations (with repetition) in MATLAB?

我專門要採取Rody Oldenhuis的答案。因此,您可以通過構建所有可能的排列:

x = unique(nchoosek(repmat([e0 e1 e2], 1, 3), 3), 'rows'); 

這將創造所有可能的排列的陣列e0e1e2。因此,使用與e0 = 1, e1 = 2, e2 = 3你的榜樣,我們得到:

x = 

    1  1  1 
    1  1  2 
    1  1  3 
    1  2  1 
    1  2  2 
    1  2  3 
    1  3  1 
    1  3  2 
    1  3  3 
    2  1  1 
    2  1  2 
    2  1  3 
    2  2  1 
    2  2  2 
    2  2  3 
    2  3  1 
    2  3  2 
    2  3  3 
    3  1  1 
    3  1  2 
    3  1  3 
    3  2  1 
    3  2  2 
    3  2  3 
    3  3  1 
    3  3  2 
    3  3  3 

現在終於得到你想要的東西,你就必須要總結過行,所以做:

y = sum(x, 2) 

y = 

    3 
    4 
    5 
    4 
    5 
    6 
    5 
    6 
    7 
    4 
    5 
    6 
    5 
    6 
    7 
    6 
    7 
    8 
    5 
    6 
    7 
    6 
    7 
    8 
    7 
    8 
    9 

你已經在用戶沒有輸入任何內容時寫下該案例來處理e0e1和/或e2,所以你只需要把你的代碼和上面寫到你的函數中。它應該給你想要的。

+0

非常感謝您的回答。這是一個很大的幫助。 – 2015-03-04 10:03:32