2015-04-06 139 views
0

這是我的代碼,我試圖寫一個矩陣作爲輸入並返回矩陣作爲輸出的matlab函數。matlab函數定義中的錯誤

a=[ 1 2 3; 4 5 6; 7 8 9]; 
function [s]= try_1(a) 
    %takes a matrix as a input 
    display(' data matrix'); 
    disp(a); 
    disp('dimension of the matrix'); 
    [m n]= size(a); %calculate the dimension of data matrix 
    s = mean(a); 
end 
+1

你有什麼錯誤? – Mehraban 2015-04-06 06:21:51

+0

錯誤是「在此上下文中不允許使用函數定義」。 – 2015-04-06 06:22:50

+0

[This](http://stackoverflow.com/questions/5363397/in-matlab-can-i-have-a-script-and-a-function-definition-in-the-same-file)可能有幫助 – 2015-04-06 06:26:05

回答

0

解釋清楚你在哪裏執行上面的代碼? 如果您在命令提示符中執行,請勿使用函數。代碼喜歡這個

a=[ 1 2 3; 4 5 6; 7 8 9]; 
    %takes a matrix as a input 
    display(' data matrix'); 
    disp(a); 
    disp('dimension of the matrix'); 
    [m n]= size(a); %calculate the dimension of data matrix 
    s = mean(a); 

,或者如果您不使用命令提示符,然後把值另一個函數「一」,並呼籲從創建新的功能try_1功能。這樣的代碼

function parent() 
a=[ 1 2 3; 4 5 6; 7 8 9]; 
s= try_1(a) 
end 

function [s]= try_1(a) 
     %takes a matrix as a input 
     display(' data matrix'); 
     disp(a); 
     disp('dimension of the matrix'); 
     [m n]= size(a); %calculate the dimension of data matrix 
     s = mean(a); 
end 

或分配則try_1函數內的值。這樣的代碼

function [s]= try_1(a) 
a=[ 1 2 3; 4 5 6; 7 8 9]; 
    %takes a matrix as a input 
    display(' data matrix'); 
    disp(a); 
    disp('dimension of the matrix'); 
    [m n]= size(a); %calculate the dimension of data matrix 
    s = mean(a); 
end 
+0

如果你解釋**爲什麼** OP會得到錯誤真的會很好。你所做的只是告訴他們他們應該做什麼。 – rayryeng 2015-04-06 06:59:15

+0

OP問問題代碼中有什麼問題?但OP不問爲什麼? – 2015-04-06 07:34:24

+0

是啊...... **代碼有什麼錯誤?你沒有告訴他們什麼是錯的。你只是告訴他們在你的代碼中做你說的話。看看接受的答案。它清楚地解釋了什麼是錯誤的,以及如何解決它。你只需要做一些事情,但不要解釋爲什麼**你應該這樣做。 – rayryeng 2015-04-06 07:35:46

3

您不能在腳本中定義函數。 MATLAB假定你的文件是一個腳本,因爲它以a=[ 1 2 3; 4 5 6; 7 8 9];開始 - 即通過定義一個變量。因此,MATLAB假定一系列指令正在執行,並在看到函數定義時引發錯誤。

您還必須區分功能定義和功能調用。與您的代碼上面,即

function s = try_1(a) 
... 
end 

定義函數功能(功能定義),但你不它,即沒有任何反應。對於發生的事情,您必須在腳本或工作區中調用

a=[ 1 2 3; 4 5 6; 7 8 9]; 
s = try_1(a); 

關於文件名以及在每個文件中應該放什麼:功能在MATLAB中由它們的文件名標識。絕對有必要在名爲try_1.m的文件中具有try_1()功能。此文件不能包含任何其他內容。 a=[ 1 2 3; 4 5 6; 7 8 9];和函數調用屬於一個單獨的腳本(或測試行爲只需在命令窗口中鍵入它)。