Create a function from another function with less parameters

조회 수: 13 (최근 30일)
Dave
Dave 2016년 11월 9일
편집: Dave 2016년 11월 9일
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

채택된 답변

Steven Lord
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
Dave
Dave 2016년 11월 9일
Thanks, this is the solution I was searching for, it was even shown in the examples of fzero, but somehow I missed it.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Geoff Hayes
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.
  댓글 수: 1
Dave
Dave 2016년 11월 9일
편집: Dave 2016년 11월 9일
Thanks for the answer, but I forgot to mention that myFunc is generated during run time. Anyway, I will keep this in mind for the future.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by