Create a function from another function with less parameters
14 次查看(过去 30 天)
显示 更早的评论
I have a function, let's call it "myFunc". myFunc accepts two parameters, x and y. I want to create a new function "myFunc2", based on myFunc, with one parameter set to a certain value. (e.g x=1)
My final goal is to be able to call the function fzero, passing Myfunc2, that will be function of y only.
Is it possible? I also accept different solutions for achieving this. Thanks in advance
0 个评论
采纳的回答
Steven Lord
2016-11-9
You can use an anonymous function.
addMe = @plus; % the plus function (equivalent of the + operator) accepts two inputs
addOne = @(x) addMe(x, 1); % accepts one input x and returns x+1
addMe(2, 3) % returns 5
addOne(2) % returns 3
更多回答(1 个)
Geoff Hayes
2016-11-9
Dave - try nesting the second function within the first (see nested functions for details. For example,
function [] = myFunc(x,y)
function [v] = myFunc2(z)
% since nested within myFunc, it has access to x
v = z + x;
end
% call myFunc2
fprintf('%d\n',myFunc2(42));
end
Of course, you would use fzero instead.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Debugging and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!