matlab曲线拟合(polyfit函数,读取文件,分隔文件内容的各列,结果写出到文件)

源数据文件:各行以tab键分隔,文件中的第一列为自变量,其他列为因变量。

x	           y1               y2                y3
-5.00E+03	-2.73E-01	-8.24E-01	5.63E+00
-4.90E+03	-2.78E-01	-8.19E-01	5.63E+00
-4.80E+03	-2.83E-01	-8.14E-01	5.63E+00
-4.70E+03	-2.88E-01	-8.09E-01	5.62E+00
-4.60E+03	-2.94E-01	-8.03E-01	5.62E+00
-4.50E+03	-2.99E-01	-7.98E-01	5.61E+00
-4.40E+03	-3.04E-01	-7.93E-01	5.61E+00
-4.30E+03	-3.09E-01	-7.88E-01	5.60E+00
-4.20E+03	-3.15E-01	-7.83E-01	5.60E+00
-4.10E+03	-3.20E-01	-7.77E-01	5.60E+00
-4.00E+03	-3.25E-01	-7.72E-01	5.59E+00
-3.90E+03	-3.31E-01	-7.67E-01	5.59E+00
-3.80E+03	-3.36E-01	-7.62E-01	5.58E+00
-3.70E+03	-3.41E-01	-7.56E-01	5.58E+00
-3.60E+03	-3.47E-01	-7.51E-01	5.57E+00
-3.50E+03	-3.53E-01	-7.46E-01	5.57E+00
-3.40E+03	-3.58E-01	-7.40E-01	5.56E+00

Matlab代码

clear
clc

fid = fopen('D:/xxx/result.txt','w');%this command will clear the file. the file will be created , if not exited.

format long %pirnt 15 fig
delimiter = '\t';
nheaderlines =1; %文件中的第一行为表头
A = importdata("D:/xxx/xxx.tab", delimiter, nheaderlines);
%A = importdata("D:/materials/WorkingProjMaterial/fromJiading/adamsKC/rear/rear_suspension_longitudinal_traction.tab", delimiter, nheaderlines);

rowsNum = size(A.data,1)%row of A
columnsNum = size(A.data,2)%columns of A
size(A.colheaders);

IndepenVariIdx = 1 %文件中的第一列为自变量,其他列为因变量
x = A.data(:,IndepenVariIdx);%first column of A.data
display("indepent varialbe name = ");
display(A.colheaders(1));

indepVarNameCell = A.colheaders(IndepenVariIdx);
fprintf(fid,'indepent varialbe name = %s  \n \n', indepVarNameCell{1,1});
curveHighestOrder = 3;%使用三次曲线进行拟合
for colunmIdx = 2: 1:columnsNum %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    y = A.data(:,colunmIdx);%one column of A.data
    %display("curve:  ")
    %display(A.colheaders(colunmIdx))
    name = A.colheaders(colunmIdx);
    fprintf(fid,'curve of %s :\n', name{1,1});
    coeffi = polyfit(x,y,curveHighestOrder); %coeffi(1) is highest order term
    colNum = size(coeffi,2);
    for i = colNum:-1:1
        fprintf(fid,'%.9f,', coeffi(i));  %将结果写入文件中
    end
    fprintf(fid,'\n \n');
end

fclose(fid);%关闭文件
display("END");

 

你可能感兴趣的:(matlab)