精華區beta MATLAB 關於我們 聯絡資訊
※ 引述《johnny4003 (股市巨量下跌)》之銘言: : 各位大大~ : 我在撰寫的時候需要用到nargin&nargout, : 但是在Help看不出要怎麼用? : 謝謝~ : function [x0, y0] = myplot(x, y, npts, angle, subdiv) : % MYPLOT Plot a function. : % MYPLOT(x, y, npts, angle, subdiv) : % The first two input arguments are : % required; the other three have default values. : ... : if nargin < 5, subdiv = 20; end : if nargin < 4, angle = 10; end : if nargin < 3, npts = 25; end : ... : if nargout == 0 : plot(x, y) : else : x0 = x; : y0 = y; : end nargin和nargout在比較大型的函式裡會用到(toolbox應該幾乎都有) 舉例來說 有個函式一開始對於輸入與輸出的設定是長這樣子 function [ A B C D ] = myfun( a , b , c , d ) 我們要使用myfun這個函式的話 多半都是直接用[ A B C D ] = myfun( a , b , c , d )即可 但事實上,可以使用nargin和nargout來做很多變化 像是我們輸入可以這樣來寫myfun( a , b )(輸出的部份稍後講,這裡先講輸入) 只輸入a和b,但是c和d沒有輸入,運算時會需要用到怎麼辦? 這時候可以使用nargin來幫c和d做一個像是預設值的動作 如果我們輸入裡有c和d,那麼後面運算就用我們輸入的c和d來運算 如果我們輸入裡沒有c和d,那麼後面的運算就使用函式內建的預設值來運算 而判斷的方法就是使用nargin nargin可以判斷你輸入了幾個變數進函式來 以前面的例子,只輸入a和b的話,nargin就會等於2 所以我們只需要在程式一開始加點判斷式來給預設值即可 if nargin == 3 % (假設輸入abc而沒有輸入d) d = 某數預設值 ; elseif nargin == 2 % (假設輸入ab而沒有輸入cd) d = 某數預設值 ; c = 某數預設值 ; end 使用這個方法可以省掉一些麻煩,像是某些迭代需要輸入的停止條件ε 當此次iteration的運算結果與上一次iteration運算結果差異小於ε時運算結束 我們可以每次都輸入個ε讓程式用 但如果覺得這樣每次都輸入很麻煩的話 我們也可以利用nargin來給預設值 不想輸入ε的話就不要輸入 判斷式檢查nargin發現少一個輸入的話,自動給個預設的ε就好 而nargout的話與nargin很類似,是判斷輸出有幾個用的 像是前面的例子 我們使用函式時也可以寫[ A B ] = myfun( a , b , c , d ) 這樣的話nargout的值為2 會需要用到nargout是因為有些資訊如果覺得不是那麼必要的話 可以使用nargout來判斷需不需要為那些不很必要的資訊做運算 上面的寫法輸出只有A和B,C和D可能是在這次使用沒有需要要看的資訊 那就使用nargout來判斷輸出只要有兩個 C和D就不要做運算了,來節省些時間 nargin和nargout的用法大致是這樣 總之就是來判斷這次要使用該函式時有輸入的多少個變數,以及需要輸出多少個變數 -- Deserves death! I daresay he does. Many that live deserve death. And some die that deserve life. Can you give that to them? Then be not too eager to deal out death in the name of justice, fearing for your own safty. Even the wise cannot see all ends. Gandalf to Frodo -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.120.25.235
Ysen:這個要M一下@@,G大真是強.. 04/11 12:40
KevinT:詳細 推!! 04/11 14:28
cute1888:推 我搞懂了ㄟ!! 04/11 17:06
oct:nargin & nargout用法書上倒是還找得到,但是說到varargin和 04/11 17:28
oct:varargout, 書上似乎都沒有很明確的使用方法 04/11 17:29
oct:只大略知道這兩個用在不確定輸入輸出的情況 04/11 17:29
oct:但是如果只是這樣的功能,不是用 nargin & nargout就可以達成 04/11 17:30
oct:了嗎? 04/11 17:30
bylankai:nargin和nangout就是指varargin和varargout的個數啊 04/11 17:53
bylankai:前者用來判斷 後者用來給這個function輸入和輸出參數 04/11 17:56