single trendline for multiple series
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Afifa Tabassum Tinni
el 6 de Oct. de 2018
i have multiple series in a plot. i want to fit a single trend for all the series. can it be done in matlab?
2 comentarios
Respuesta aceptada
jonas
el 6 de Oct. de 2018
Let's say you have single column arrays x1, x2, x3 and their corresponding y1, y2 ,y3.
%%concatenate
x = [x1;x2;x3];
y = [y1;y2;y3];
%%fit linear trend
p = polyfit(x,y,1)
%evaluate at points xp
yp = polyval(p,xp)
there is your linear trendline, [xp yp]. If you want a higher polynomial, just change the number in polyfit
0 comentarios
Más respuestas (1)
dpb
el 6 de Oct. de 2018
Sure, just group all the independent and dependent data arrays into one long vector for each.
Presuming you have X,Y arrays such that
hL=plot(X,Y);
then
f=fit(X(:),Y(:),'poly1')
hold on
plot(f)
2 comentarios
dpb
el 6 de Oct. de 2018
Editada: dpb
el 6 de Oct. de 2018
You said you had multiple plots on a graph; I simply assumed that was done by having already created an array of X, Y by column so could create the plot in a single call as shown.
"(:)" is a Matlab syntax idiom that returns all values of an array of any size as a column vector so that's the form needed by fit so you automagically get a fit of all data values without having to do any additional creation of other variables.
It is counter-productive in Matlab to create sequences of similar variables with sequential letters or numbers; then you run into the problem you have above of having to explicitly code for those variable names instead of being able to use generic code for any given number of variables which could change.
But, if you do already have the figure and it was created by adding lines sequentially even if they have individual names as x1,y1, x2,y2, ..., all is not lost! :)
hAx=gca; % get the current axis handle as variable axis handle
hL=hAx.Children; % return handle array to lines on the axis
X=get(hL,'XData'); X=[X{:}].'; % get plot XData; arrange as column vector
Y=get(hL,'YData'); Y=[Y{:}].'; % ditto for YData
Now you have the necessary X, Y arrays to fit all data on the plot together without having to had to have known the individual variable names or even how many of them there were. Much easier, no? :)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!