How to turn a function handle with 3 inputs (1 variable and 2 parameters) and then assign the inputs parameters and get a function handle with one input? ?
조회 수: 3(최근 30일)
Consider the following
Now, I would like to create another function handle which is only a function of x. You migh suggest the following solution:
but this is not what I want since I need to pass g(x) as input to another function and there I want to reduce the computational time. If I follow this solution whenever I call g, say g(1), it needs f, too plus that it does 3 arithmatics (3 sums) but I would like to have 2 arithmatics since g(x)=x+2.
Steven Lord 2022년 1월 14일
Let's look at the actual time difference between the two approaches.
h = @(x) x+2;
Is this really the bottleneck in your code?
I realize that this was probably just a simple example to demonstrate what you're trying to do, so can you show the output of timeit called on a more "realistic" f, g, and h functions from your actual application?
Jeff Miller 2022년 1월 15일
Not sure I understand the situation, but this sounds to me like a case where an OO approach could be very helpful. Consider:
classdef myFunc < handle
function obj = myFunc() % Constructor
obj.ComputedFromYandZ = 0;
function  = SetNewYandZ(obj,Y,Z) % Compute whatever depends on Y and Z
obj.ComputedFromYandZ = Y + Z;
function Result = ComputeFromX(obj,X) % Compute whatever depends on X with Y and Z fixed
Result = abs( X + obj.ComputedFromYandZ ) ;
% I included abs() here to make a function for fminsearch to
You can then use a function handle to a function that depends only on X (after setting Y and Z), something like this:
myF = myFunc;
% ans -5
% ans 50