Re: [問題] MATLAB寫主函數與子函數~已回收

看板MATLAB作者 (凱文踢)時間16年前 (2009/03/12 20:49), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)
※ 引述《jay750719 (jaylin)》之銘言: : 我想要在一個M檔中,寫一個主程式再去呼叫子函式 : 可是書中的範例很少,我不是很懂,誰有多一點的 : 範例與說明可以提供給我. 小的弱弱的 把我知道的用例子分享一下... %% 這是示範的test.m %% function output = test(input) % 如你所見 因為你說要在"一個"m file裡 % 建立主程式跟子函式 所以第一件事就是 % 主程式也必須是個function 而不是script global input2; input2 = 10; % global varible 可以在不同function裡面傳來傳去 % 但是危險是你可能在不知覺中用了相同的參數名稱 % 改掉了之前設定的參數值 要小心 % 設這個是為了跟local varible "input"作比較 disp('the local varible input = '); disp(input); disp('the global varible input2 = '); disp(input2); output_Func = myFunc(input, input2); % 呼叫方式只要名稱一樣就好 % 此例來說 subfunction叫myFunc % 呼叫就是依照指定的input output形式打 disp('the subfunction output = '); disp(output_Func); disp('the local varible AFTER subfunction = '); disp(input); % local varible沒變 一樣是你輸入的值 disp('the global varible AFTER subfunction = '); disp(input2) % 但是global varible變了 因為你在subfunction改變了他 output = input + input2; % 這邊會用主程式的local varible input % 加上更改過得global varible input2 % 當作主程式的output %% 以下是子函式 function cc = myFunc(aa, bb) % 你可以發現其實跟一般function寫法一樣阿XD % input進來的名稱可以改 不一定要跟主程式輸入的參數名稱相同 % 此例來說 主程式輸入input跟input2 但是在子程式我叫他aa跟bb global input2; % global varible在subfunction 還得宣告一次...orz input = 2; % 這邊也有個叫input的 數值是2 input2 = 3; % input2我們之前設定為global 把他改成3了 disp('local varible input in the subfuction = '); disp(input); disp('global varible input2 in the subfunction = '); disp(input2); cc = aa + bb; -- 以上程式使用方式: 請在command window打上 >> out = test(18) 當然 input原則上爽傳什麼都可以啦 本例不要輸入2就好了 請注意 只有傳出來的值(在command window打的 out)才會出現在workspace裡面 所以你有任何需要再作處理的值或是矩陣 請回傳出來 啦哩啦鉔寫一堆 希望有幫你釐清一些東西... -- ╔═╦═╗ ╔═╗ ╔═══╗ ╭──╮ ║ ║╔══╗╔═╦╗╔═╗╔══╗║ ║ ╰╮ ║ ╣║ ═ ║║ ║║ ║║ ║║ ║ ║ ║║ ╣║ ║║ ║║ ║╚╗ ╔╝ ╚═╩═╝╚══╝╚══╝╚═╝╚═╩╝ ╚═╝ →→→→ http://www.wretch.cc/album/kevint ←←←← By luh4 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.148.130 ※ 編輯: KevinT 來自: 140.112.148.130 (03/12 21:09)
文章代碼(AID): #19kGIzWw (MATLAB)
文章代碼(AID): #19kGIzWw (MATLAB)