single trendline for multiple series

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 个评论

What does this mean?
fit a single trend
yes. for example i have series 1,series 2, series 3 on a single plot. i can fit a line through each of the series individually. but if i want to fit a line through all of the series, how to do that?

请先登录,再进行评论。

 采纳的回答

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

更多回答(1 个)

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 个评论

thank you so much. just to be sure, are you telling me to combine x and y values of all the series and then make single x and y arrays?
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? :)

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by