2017-07-18 117 views
0

我想拼接參數列表以傳遞給函數。對於矢量我知道我可以使用num2cell並用大括號(請參閱this question)調用單元格,但在我的情況下,我想要拼接的列表最初有struct s,我需要訪問它們的一個屬性。例如:將函數調用的參數列表轉換爲參數 - Matlab

austen = struct('ids', ids, 'matrix', matrix); 
% ... more structs defined here 

authors = [austen, dickens, melville, twain]; 

% the function call I want to do is something like 
tmp = num2cell(authors); 
% myFunction defined using varargin 
[a,b] = myFunction(tmp{:}.ids); 

上面的例子不工作,因爲預期Matlab的從大括號ONE輸出和它的接收如圖4所示,一個用於每個作者。我也試圖定義我的參數列表作爲首位

indexes = {austen.ids, dickens.ids, melville.ids, twain.ids}; 
[a,b] = myFunction(indexes{:}); 

但這個問題是myFunction走的是矢量ids的聯合和交集,我得到以下錯誤的單元陣列:

Error using vertcat 
The following error occurred converting from double to struct: 
Conversion to struct from double is not possible. 

Error in union>unionR2012a (line 192) 
    c = unique([a;b],order); 

Error in union (line 89) 
    [varargout{1:nlhs}] = unionR2012a(varargin{:}); 

這樣做的正確方法是什麼?問題是我會有數十位作者,我不想通過手動將他們中的任何一個傳遞給myFunction

+0

能給你更多關於'id和'matrix'的信息,這樣你的代碼就可以重現嗎?另外,由於'authors'是一個結構體,你有沒有考慮過使用'struct2cell'而不是'num2cell'? – kedarps

+0

對不起,'ids'是整數的(列)向量,'matrix'是一個實數矩陣。感謝您指點我正確的方向! 'struct2cell'完成任務! – rodrigolece

+0

太棒了,很高興我能幫到你! – kedarps

回答

0

正如@kedarps正確指出我需要使用struct2cell而不是num2cell。下面的代碼的竅門

tmp = struct2cell(authors); 
[a, b] = myFunction(tmp{1,:,:}); %ids is the first entry of the structs 

我從來沒有聽說過struct2cell!它甚至不顯示在help num2cell的另見!有一個apropos函數like Julia's ....