how can write this in matlab ?

1 view (last 30 days)
Kadri Qevani
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.

Accepted Answer

Star Strider
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
Kadri Qevani
Kadri Qevani on 26 Jan 2015
Edited: Star Strider on 26 Jan 2015
% clear
clear all
close all
clc
% Simple example
x = [ 0.0 2.0 2.7 3.0 4.0] ;
y = [1.5 2.5 3.5 5.0 7.5] ;
Y = log(y);
X = x ;
s_X = sum(X);
s_Y = sum(Y);
s_X_2 = sum(X.^2);
s_XY = sum(X.*Y);
N = length(X) ;
B = (s_XY-(s_X_2*(s_Y/s_X)))/(s_X-(s_X_2*N/s_X)) ;
A = (s_Y - N*B)/s_X;
C = exp(B);
xx = zeros(1,100) ;
yy = zeros(1,100) ;
jj=1;
span = (max(X)-min(X))/100;
for x_i = 0:span:max(X)
xx(jj) = x_i;
yy(jj) = C*exp(A*x_i);
jj=jj+1;
end
hold on
plot(x,y,'kh')
plot(xx,yy)
legend('exemple', 'graph ')
hold off
something like this??
Star Strider
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.

Sign in to comment.

More Answers (0)

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!