Unable to recognise function from called script
8 ビュー (過去 30 日間)
古いコメントを表示
I created this function in a scipted named "lab1_script.m":
t = [1, 2, 3, 4]
function y = lab1_function(t, c)
y = c*t.^2;
end
But when I try to call the script in a new script as follows:
lab1_script;
y = lab1_function(t,0.1)
The error message: unrecognisable function or variable 'lab1_function' appears. And I know that the function works, because when I call it within the same script it is fine. It is just trying to call it into a different script that I am having trouble with.
I am confused, what am I doing wrong? Should I be calling the script a different way for the function to be recognised?
Thanks in advance! :)
2 件のコメント
Stephen23
2024 年 8 月 23 日
編集済み: Stephen23
2024 年 8 月 23 日
"I created this function in a scipted named "lab1_script.m""
t = [1, 2, 3, 4] % <---------------- !!!!! DELETE THIS LINE !!!!
function y = lab1_function(t, c)
y = c*t.^2;
end
When you added that line of code you turned the Mfile into a script with a local function:
Local functions are only callable from within the same Mfile.
採用された回答
Torsten
2024 年 8 月 23 日
The script should be
t = [1, 2, 3, 4];
y = lab1_function(t,0.1)
the function should be
function y = lab1_function(t, c)
y = c*t.^2;
end
Or alternatively you can use two nested functions:
lab1_script
function lab1_script
t = [1, 2, 3, 4];
y = lab1_function(t,0.1)
function y = lab1_function(t, c)
y = c*t.^2;
end
end
その他の回答 (2 件)
arushi
2024 年 8 月 23 日
Hi Alexandra,
"t = [1, 2, 3, 4]" should be defined inside the function.
In MATLAB, functions defined within a script are local to that script and cannot be accessed from other scripts or the command line. To resolve this, you should define your function in a separate file or convert your script into a function file.
Hope this helps.
Steven Lord
2024 年 8 月 23 日
Local functions in a script are only directly callable from within that script file. You could call them indirectly by calling the script and having it create a function handle to the local function. As long as the function handle was created inside the script, even if it's used outside the script it will be able to call the local function.
For example I created this script:
fh = @mylocalfunction;
fh("inside script");
function mylocalfunction(whereCalled)
fprintf("The local function mylocalfunction was called %s", whereCalled)
end
When I ran it in my MATLAB Online session the output was:
>> example2147479
The local function mylocalfunction was called inside script
Then I typed one more line in the Command Window and the output was:
>> fh("outside script")
The local function mylocalfunction was called outside script
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!