- all anonymous function inputs are @(x)
- all p factors are scalars
- There is 1 p factor for each anonymous function.
Multiplying a function stored in a function handle by a constant
11 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Adam Danz
2019-11-24
编辑:Adam Danz
2019-11-24
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.
% 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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!