Info

This question is closed. Reopen it to edit or answer.

Function of matlab.

3 views (last 30 days)
A s
A s on 28 Apr 2017
Closed: MATLAB Answer Bot on 20 Aug 2021
Could you please explain to me the general Idea how to write a function in matlab?
I was wrote code for original queistion which is f(x)=-2x^2+Lx If the Constraints x is in the feasible set [0,L/2] and it's work with me. But I'm not sure how to make a derivation If the df/dx= -2x + L;
And how can I write a function that numerically solves df/dx = -4x+ L=0

Answers (2)

Star Strider
Star Strider on 28 Apr 2017
Edited: Star Strider on 28 Apr 2017
For numeric functions, see the documentation on Function Basics (link). For Symbolic Math Toolbox functions, see the documentation on Create Symbolic Functions (link) in R2012a and later versions.
Example
syms L x
f(x) = -2*x^2 + L*x
dfdx = diff(f)
x_sol = solve(dfdx == 0)
f(x) =
- 2*x^2 + L*x
dfdx(x) =
L - 4*x
x_sol =
L/4
You can create anonymous functions (or function files) from them with the matlabFunction function that will do numeric calculations in MATLAB not using the Symbolic Math Toolbox. See the documentation on the various functions for details.

Image Analyst
Image Analyst on 28 Apr 2017
Numerically you can make an x with, say, a hundred thousand points or whatever.
x = linspace(0, L/2, 100000);
Now make the derivative:
dfdt = -4 * x + L; % or -2 * x + L, whatever one you're solving for.
Now find the element where it's closest to zero
[minValue, index] = min(abs(dfdt));
Now use that index to get the x value and f(x) value - I assume you know how to do that. Depending on L, and what equation you're using, there may be no solution.

This question is closed.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!