- 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
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jennifer Garrison
el 24 de Nov. de 2019
Comentada: Jennifer Garrison
el 25 de Nov. de 2019
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 comentarios
Respuesta aceptada
Adam Danz
el 24 de Nov. de 2019
Editada: Adam Danz
el 24 de Nov. de 2019
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);
Más respuestas (0)
Ver también
Categorías
Más información sobre Graphics Object Programming en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!