how can write this in matlab ?
1 view (last 30 days)
Show older comments
Kadri Qevani
on 25 Jan 2015
Commented: Star Strider
on 26 Jan 2015
I want to make one M-file that finds a function P(x)=A*e^M*x, which can approximate a function that is given in tabular shape.
0 Comments
Accepted Answer
Star Strider
on 25 Jan 2015
Assuming that ‘A’ and ‘M’ are matrices, and that ‘x’ is a vector:
function Z = P(A, M, x)
for k1 = 1:length(x)
P(:,:,k1) = A*expm(M*x(k1)); % Anonymous Function
end
end
Call it as:
N = 3; % Matrix Size
A = rand(N); % Create Random Matrix To Test Code
M = rand(N); % Create Random Matrix To Test Code
x = linspace(0, 1, 10); % Create ‘x’ Vector
Z = P(A, M, x); % Z = A*expm(M*x)
8 Comments
Star Strider
on 26 Jan 2015
Actually, I believe this is what you want to do:
x = [ 0.0 2.0 2.7 3.0 4.0];
y = [1.5 2.5 3.5 5.0 7.5];
P = @(b,x) b(1).*exp(b(2).*x); % Regression Model
SSECF = @(b) sum((y - P(b,x)).^2); % Sum-Squared-Error Cost Function
B0 = rand(2,1); % Initial Paremeter Estimates
[B, SSE] = fminsearch(SSECF, B0); % Estimate Parameter Vector ‘B’
xplt = linspace(min(x), max(x)); % Vector Of ‘x’ To plot
figure(1)
plot(x, y, 'bp') % Plot Data (Blue Stars)
hold on
plot(xplt, P(B,xplt), '-r') % Plot Function Fit (Red Line)
grid
text(0.6, 6.5, sprintf('P(x) = %.4f\\cdote^{%.4f\\cdotx}', B))
It uses the fminsearch function and the sum-squared-error cost function, ‘SSECF’ with your ‘P’ function (where ‘A’ = ‘b(1)’ and ‘M’ = ‘b(2)’) to perform a nonlinear regression, and produces this plot:
Note that with the text call, the plot displays the function and the values of the estimated parameters as well.
More Answers (0)
See Also
Categories
Find more on Descriptive Statistics 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!