Function, input number, return a value
1,044 次查看(过去 30 天)
显示 更早的评论
QUESTION:
Write a small function which takes as inputs; a number a and a function g(x), and returns (a, g(a)). Note that printing is not the same as returning a value. Use the function g(x) = 2x 2 and a = 4 to test your function.
So my function right now looks like this.
function [a g(x)] = mysmallfunction(x)
a = x;
g(x) = 2*x.^2;
end
And I'm calling it like this:
clear;
[a g(x)] = mysmallfunction(4)
I get the error "Undefined function or variable 'mysmallfunction'."
But also I'm using a specific equation in 2x^2. How do I make it work for any equation.
0 个评论
采纳的回答
Guillaume
2015-4-29
编辑:Guillaume
2015-4-29
As per the question, the function you have to write takes two inputs, a number and a function (see function handles) and returns two outputs, the original number and another number. Therefore you must have two variable names before the = in your function declaration and two variable names in the brackets of your function declaration.
Note that g(x) is not a valid variable name.
To get you started, the following declaration would work:
function [a, ga] = mysmallfunction(x, g)
5 个评论
Guillaume
2015-4-29
No, you do not include the declaration of the function handle inside your own function, the function handle is one of the argument you pass to your function. That is, to test your function you would call it with
[a, ga] = mysmallfunction(4, @(x) 2*x^2);
Or to be more explicit:
g = @(x) 2*x^2
[a, ga] = mysmallfunction(4, g);
You only need to work out how to use the function handle inside your own function. I've shown you how in my previous comment.
更多回答(1 个)
Pratik Bajaria
2015-4-29
Hello,
You just have to change a few things and it must work. Atleast it does for me. ;-) you need not write g(x) literally.
function [a g] = mysmallfunction(x)
a = x;
g = 2*x.^2;
end
Call it like this:
clear;
[a g] = mysmallfunction(4)
Check and let me know if it works for you. I assume, i have got your problem right.
Regards, Pratik
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Direct Search 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!