필터 지우기
필터 지우기

least square curve fit

조회 수: 1 (최근 30일)
sanket neharkar
sanket neharkar 2022년 6월 16일
댓글: Walter Roberson 2022년 6월 17일
i have written a code for least square fit and it is taking lot of time to plot the data
i want someone to verify it and update it so that i could get appropriate results within less time
% function phi = curvefit3(x,y)
clear all;
close all;
clc;
[data, ~] = xlsread('file name.xlsx');
x_imp = data(:,1); %%reading rows and first column
y_imp = data(:,2); %%reading rows and second column
[rows, ~] = size(data);
dx = mean(diff(x_imp));
points_curve_fit = 5:2:9;
i = 0;
for nwindow = points_curve_fit
i = i+1;
for k = 1: 1 : rows -nwindow %%loop to read i+1 to i+5 rows
x = x_imp(k:k+nwindow-1,1);
y = y_imp(k:k+nwindow-1,1);
x0 = x(1);
var1 = x - x0;
var2 = var1.*var1;
%% construction of the least-squares quadratic fit to the data
%% we use the equation y =a0 + a1t + a2t^2 %%t = (x-x0)
%% numbers a0,a1 and a2 are the unknowns
x_mat = [ones(nwindow,1) var1 var2];
amat = x_mat'*x_mat;
bmat = x_mat'*y;
phi = inv(amat)*bmat;
a0 = phi(1);
a1 = phi(2);
a2 = phi(3);
error = y-(x_mat*phi);
marker = floor(nwindow/2) + 1;
if (k == 1)
err(1:marker,1) =error(1:marker,1);
else
err(k+marker-1) =error(marker);
end
pos_n = (a0+a1*var1+a2*var2);
markar = floor(nwindow/2) + 1;
if (k == 1)
pos(1:markar,1) = pos_n(1:markar,1);
else
pos(k+markar-1) = pos_n(markar);
end %if (i == 1)
velo = gradient(pos,dx);
acc_n = gradient(velo,dx);
end
% store iteration results into 2D array (1 iteration = 1 column)
err_all(:,i) = err; % to plot all outputs
pos_all(:,i) = pos; % to plot all outputs
velo_all(:,i) = velo; % to plot all outputs
acc_n_all(:,i) = acc_n; % to plot all outputs
n= length(pos);
tim_pos = x_imp(1:n);
tim_velo = x_imp(1:n);
tim_acc_n = x_imp(1:n);
y_raw = y_imp(1:n);
fig1 = figure('name', sprintf('%d points curve fit', points_curve_fit),'NumberTitle','off');
plot(tim_pos,y_raw,'or',tim_pos,pos','-g',tim_velo,velo_all','--k',tim_acc_n,acc_n_all','--y'); grid on;
legend([{' raw data','position','velocity','acceleration'}]);
xlabel(' Time(sec) ');
ylabel(' Function ');
end
fig2 = figure('name','errors' ,'NumberTitle','off');
plot(tim_pos,err_all,'--');grid on;
legend('error 5 pts','error 7 pts','error 9 pts');
  댓글 수: 4
sanket neharkar
sanket neharkar 2022년 6월 17일
okk i did that
i want to update my 3 figures with the names as the for loop
for first fig it should come as 5points curve fit then
7point curve fit
9 point curvefit
plzz help me in that
Walter Roberson
Walter Roberson 2022년 6월 17일
title(points_curve_fit + " point curve fit")
Note that double quotes instead of apostrophe is important here.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Spline Postprocessing에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by