The graph basic fitting tool accepts a matrice but not the polyfit function... How to do the same thing in a script ?
1 view (last 30 days)
Show older comments
Jacques Larue
on 27 Mar 2023
Answered: Image Analyst
on 28 Mar 2023
I made a graph of the evolution of a variable through 10 time periods (colums) for 10 individuals (lines). The graph basic fitting gives a nice fourth degree fit which I want to reproduce in a script for different variables. I tried with polyfit but it doe not take a matrice as input. Could somebody tell me how to replicate the treatment of the basic fittiing tool in a script ? Here is the graph and the data in DATA.mat attached file.
Thanks alot for any help.
0 Comments
Accepted Answer
Image Analyst
on 28 Mar 2023
Try this:
% Optional initialization steps
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 18;
% Load user's data.
s = load('DATA10Curves.mat')
vcz = s.vcz;
[rows, columns] = size(vcz)
% Make dat for all of them
xAll = zeros(1, rows * columns);
yAll = zeros(1, rows * columns);
% Scan each person's data adding them to a master array.
for row = 1 : rows
% Timepoints for an individual are in columns,
% so one row is all the times for one individual.
y = vcz(row, :);
% Polyfit can't take multiple y values for the same x value,
% so let's add a very very small amount of noise to the x values.
% It won't be enough to affect the fit.
smallNoise = 0.001 * (rand(1, columns) - 0.5); % Zero mean noise.
x = (1 : columns) + smallNoise;
plot(x, y, '.-', 'LineWidth', 2, 'MarkerSize', 15);
grid on;
hold on;
% Store in our master array.
startingIndex = (row - 1) * columns + 1;
endingIndex = startingIndex + columns - 1;
xAll(startingIndex : endingIndex) = x;
yAll(startingIndex : endingIndex) = y;
end
% It's not needed but let's sort by x anyway.
[xAll, sortOrder] = sort(xAll, 'ascend');
yAll = yAll(sortOrder);
% Fit to a 4th order equation.
coefficients = polyfit(x, y, 4);
% Get fitted values at the 10 original x points.
xFit = 1 : columns;
yFit = polyval(coefficients, xFit);
% Plot fitted line in black over the other curves.
plot(xFit, yFit, 'k-', 'LineWidth', 5);
hold off
xlabel('x', 'FontSize', fontSize);
ylabel('y', 'FontSize', fontSize);
0 Comments
More Answers (1)
Antoni Garcia-Herreros
on 27 Mar 2023
Hello,
Something like this might do the trick:
close all
for i=1:10; % Loop through your variables
p=polyfit([1:10]',vcz(:,i)',4);
YT=polyval(p,T);
p1=plot([1:10],vcz(:,i));
L=legend;
hold on
p2=plot(T,YT,'LineWidth',2);
L.String{end}=['Fitted ' L.String{end-1}];
end
Hope this helps!
See Also
Categories
Find more on 2-D and 3-D Plots 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!