How to call a created function in a different function

23 ビュー (過去 30 日間)
Jongan Park
Jongan Park 2020 年 1 月 14 日
編集済み: Stephen23 2021 年 7 月 27 日
Hi there!
I made several functions like myfunc1.m , myfunc2.m, myfunc3.m and so on.
they all take one function and two doubles, and they output 2 arrays like this.
function [X Y] = myfunc3(f, a, b)
% ------------------------
% --Doing Something like--
% -- x = a:b --
% -- y = 3*x --
% -- X = x --
% -- Y = f(x,y) --
% ------------------------
end
Im trying to make a new function that takes one of my functions as its argument. Expected outputs will be like this.
>> myNewfunc(@ myfunc3)
ans =
'It is my 3rd function!'
>> myNewfunc(@ myfunc2)
ans =
'It is my 2nd function!'
so I wrote like this to call a function in the new function
function myNewfunc(myfunc)
% --------------------------------
% -- %Hard Coded f, a, b --
% -- f = @(x,y) x + y --
% -- a = 1 --
% -- b = 10 --
% -- [X Y] = myfunc(f,a,b) --
% --------------------------------
%
%Somehow Check and disp its number
%
end
but it gets an error at the line of [X Y] = myfunc(f, a, b) and shows "Reference to a cleared variable myfunc."
How can I tell Matlab I am trying to call one of created functions in another function?
Thank you! and any help will be appreciated.

採用された回答

Stephen23
Stephen23 2020 年 1 月 14 日
編集済み: Stephen23 2021 年 7 月 27 日
Download my FEX submission num2ord and use it together with func2str:
function out = myNewFunc(fun)
val = str2double(regexp(func2str(fun),'\d+$','once','match'));
out = sprintf('It is my %s function!',num2ord(val));
end
Tested:
>> myNewFunc(@myfunc3)
ans =
It is my 3rd function!
See also:
Tip: rather than creating numbered functions, which will be hard to access and just clutter up the workspace, you might like to consider simply creating a cell array of function handles (which can be trivially accessed using indexing):
C = {@(...)..., @(...)..., ...} % define
C{1}(...) % call the first function
  1 件のコメント
Jongan Park
Jongan Park 2020 年 1 月 14 日
Thank you so much for the detailed answer and useful tip!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by