2014-11-06 133 views
2

我注意到,如果我們想將一個向量賦值給幾個變量,我們可以使用'deal';但是當將一個矩陣分配給幾個向量時,它不起作用。例如如何一次爲幾個向量分配一個矩陣?

A=[1 2; 3 4]; 
A=num2cell(A); 
[a, b]=deal(A{:}) 

它給出了一個錯誤信息"Error using deal (line 38) The number of outputs should match the number of inputs."

你知道如何改進代碼?謝謝!!

+1

嘗試編輯你的答案提供有關環境,編程語言等詳細信息,如寫有沒有很多有用的信息,可以用於幫你。 – par 2014-11-06 23:08:30

回答

0

你可以非常伊斯利編寫自己的交易:

# in mydeal.m 
function varargout = mydeal(varargin) 
    % Assign values in vector into variables. 
    % 
    % EXAMPLE 1 
    % [a,b,c] = mydeal([1,2,3]); 
    % EXAMPLE 2 
    % some_vector = [1,2,3]; 
    % [a,b,c] = mydeal(some_vector); 
    % 
    % %results in a=1, b=2, c=3; 
    % 


    assert(nargout == size(varargin{1}, 2), 'Different number of in and out arguments'); 

    for i = 1:nargout 
     varargout{i} = varargin{1}(:, i); 
    end 

例如:

>> [a,b] = mydeal([1 2; 3 4]) 

a = 

    1 
    3 


b = 

    2 
    4 

或者

>> [a,b, c] = mydeal([1 2 3]) 

a = 

    1 


b = 

    2 


c = 

    3 
0

你幾乎得到了解決,但你的代碼分裂阿成具有標量元素的2x2單元格。使用的num2dell第二個輸入參數分裂成列向量:

A=[1 2; 3 4]; 
A=num2cell(A,1); 
[a, b]=deal(A{:}) 
相關問題