MATLAB: Multiplying a function stored in a function handle by a constant

anonymous functionchange function handlecombine function handlesfunction handlesMATLAB

fBasis = { @(x)sin(x) , @(x)sin(2*x) , @(x)sin(3*x) }
p = [2, 0, 0.5] end code
Your function would return the handle to a function that computes y = 2sin(x) + 0.5sin(3x).
How would you do something like this? I know it is not possible to multiply a function handle by a contant and for this poblem, I do not know what kinds of functions will be inputted in the array fBasis. Yes this is a small portion of a homework question but we are allowed to ask for help. A nudge in the right direction about how to start this would be very much appreciated.

Best Answer

One approach would be to get the outputs to your fBasis functions and then multiply by p as you describe in your question. Here's a demo of that method.
x = 1:10; % Can be a vector, matrix, n-d array, etc.
vals = cellfun(@(f,p)p*f(x(:)),fBasis,num2cell(p),'UniformOutput',false);
y = reshape(sum(cell2mat(vals),2),size(x));
Another approach would be to add the p factors into your functions by converting the function handles to char arrays, factoring in the p values, combining all 3 function strings, and then converting back to an anonymous function.
Here are the assumptions that need to be met.
  • all anonymous function inputs are @(x)
  • all p factors are scalars
  • There is 1 p factor for each anonymous function.
% Input (from the question)
fBasis = { @(x)sin(x) , @(x)sin(2*x) , @(x)sin(3*x) };
p = [2, 0, 0.5];
% Convert to char arrays, remove @(x) and add the factors in p
fStr = cellfun(@(f,c) strrep(func2str(f),'@(x)',...
sprintf('%.5g*',c)),fBasis,num2cell(p),'UniformOutput',false);
% Combine all equations with +
fstrLong = strjoin(fStr,' + ');
% Convert back to an anonymous function
finalFunc = str2func(['@(x)',fstrLong]);
% Test it
x = 1:10; % row vector input
y = finalFunc(x)
x = (1:10)'; % Column vector input
y = finalFunc(x)
x = magic(5); % matrix input
y = finalFunc(x);