I tried to run a script with a function, but my function input name show 'the function might be unused'. Please help anyone?
Show older comments
Hello Everyone. I have tried to make a function in matlab for the following function:
f(x) = x*(e^x)
Now I have used the code function to describe my function (which I called fun1) and placed the equation as follows:

However, When I try to run the function or place a value of x in the command window, I notice the following in my script:

Any help on how to solve this and how to make a code so I could solve this function for any value of x please? I have not any experience of matlab in the last 5 years and I have the 2020 version so I am a little lost on this.
Thanks!
Answers (2)
Walter Roberson
on 24 Aug 2020
0 votes
The warning is correct.
Your script defines Fun1 but it never calls Fun1. Just defining a function does not invoke the function.
7 Comments
Clayton Milla
on 24 Aug 2020
Image Analyst
on 24 Aug 2020
What if you do this on line 11:
f = Fun1(0.42)
If you don't like that, then plug in some different value for x.
Clayton Milla
on 24 Aug 2020
Image Analyst
on 24 Aug 2020
It only works for a scalar. If you want it to work with a vector x, you have to use .* instead of *.
f = x .* exp(x); % Now x can be a scalar or an array.
Walter Roberson
on 24 Aug 2020
Yes, the code will only work for a scalar or an empty array.
Clayton Milla
on 24 Aug 2020
Walter Roberson
on 24 Aug 2020
My problem here is that I would like to just input any value of x and this equation can solve it.
This equation can solve what ?
Image Analyst already shows how you can invoke Fun1 with arbitrary input like 0.42 . However, that does not "solve" any equation.
Your function needs to accept a function handle, a lower bound (a), an upper bound (b), a number of steps to use (N). It needs to calculate a series of x values, N in total, the first of which is a and the last of which is b, and the (N-2) remaining are equally spaced in-between. Then it needs to invoke the function handle on each of the x values, getting f(x_j) values. Sum them, divide by N.
Steven Lord
on 24 Aug 2020
Rather than defining the Fun1 function as a function inside the script hmwk1_problem1a.m I would define it as a regular function in a file my_fun.m. The whole contents of my_fun.m should be:
function f = my_fun(x)
f = x*exp(x); % Or the vectorized version posted by Image Analyst
end
There's no need to clear all variables, clear the command window, and close all figures every time you (or your professor) runs your script.
If you haven't used MATLAB for five years, you may be a little rusty. I recommend going through the free MATLAB Onramp tutorial to refresh your memory.
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!