Plotting multiple graphs in one figure

2 views (last 30 days)
Hello, I am new to matlab and have written a code to create a custom fit for data. I am hoping to plot multiple data sets with this fit in one figure. Currently, this code runs but it creates an individual plot for each data set, which is not what I want. Also, I am having difficulty with the legend formatting. I want to make each line a different color and label as y1,y2,y3... but what I have been currently doing is not working. Thank you.
%% create figure for each data set
w={}; %to collect coefficient values
hold all
for i=1:1:u %where u is the final column of y values
[xData, yData] = prepareCurveData( X, y );
ft = fittype( 'a*exp(-b*x)', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
opts.StartPoint = [0.893783889527977 0.298767974365371];
% Plot fit with data.
figure( 'Name', ['y',sprintf('%d',i)] );
% Fit model to data.
[fitresult{i}, gof(i)] = fit( xData, yData, ft, opts );
hold all % from here downwards is where I find difficulty plotting correctly
for j=1:1:u
h = plot( fitresult{i}, xData, yData);
v =coeffvalues(fitresult{i});
w =[w v];
hold off
% Label axes
xlabel X
ylabel y_i
grid on
hold off
amy gravenstein
amy gravenstein on 2 Mar 2020
I start with a 4 by 14 matrix. X is the first column of the matrix. Y is the remaining 4 by 13 matrix. u is the number of columns in Y which is 13. w and v are used to gather the coefficient values. If there is anything more you need please let me know. Thanks!

Sign in to comment.

Accepted Answer

Jalaj Gambhir
Jalaj Gambhir on 2 Mar 2020
The problem is specifying creation of a figure inside the outer for loop. You can declare it outside, specifying a uniform title (because you want a single figure), and removing the first 'hold off' command (just outside the inner for loop)
Hope this helps!

More Answers (0)


Find more on Line 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!

Translated by