Adding a legend for different data sets

14 views (last 30 days)
BobbyJoe
BobbyJoe on 2 Feb 2021
Answered: Star Strider on 3 Feb 2021
Hi I have the following code:
function API1
function C=kinetics(theta,t)
c0=[0.575;0.748;0]; %Initial Concentration
[T,Cv]=ode45(@DifEq,t,c0);
function dC=DifEq(t,c)
dcdt=zeros(3,1);
dcdt(1)=-theta(1).*(c(1).^1).*c(2).^1;
dcdt(2)=-theta(1).*(c(1).^1).*c(2).^1;
dcdt(3)=theta(1).*(c(1).^1).*c(2).^1;
dC=dcdt;
end
C=Cv;
end
T = [0 10 20 30]; %X coordinates
t = T';
%Y values for A
a_ydata = [0.575 0.1611725 0.10373 0.0999925];
A_Ydata = a_ydata';
%Y values for B
b_ydata = [0.748 0.3336725 0.27623 0.2724925];
B_Ydata = b_ydata';
%Y values for C
c_ydata = [0 0.4138275 0.47127 0.4750075];
C_Ydata = c_ydata';
c = [A_Ydata B_Ydata C_Ydata];
theta0=[0.5]; %Initial guess
[theta,Rsdnrm,Rsd,ExFlg,OptmInfo,Lmda,Jmat]=lsqcurvefit(@kinetics,theta0,t,c);
fprintf(1,'\tRate Constants:\n')
for k1 = 1:length(theta)
fprintf(1, '\t\tTheta(%d) = %8.5f\n', k1, theta(k1))
end
tv = linspace(min(t), max(t));
Cfit = kinetics(theta, tv);
figure(1)
h = plot(t, c,'.');
set(h,{'Marker'},{'s';'d';'^'},{'MarkerFaceColor'},{'r';'b';'k'},{'MarkerEdgeColor'},{'r';'b';'k'});
hold on
hlp = plot(tv, Cfit,'LineWidth',1.5);
set(hlp,{'Color'},{'r';'b';'k'});
hold off
grid
xlabel('Time (min)')
ylabel('Concentration (M)')
legend(hlp, 'Rif', 'Tert', 'Oxazine', 'Location','N')
Cfit_mtx = kinetics(theta, t); % Calculate R² For Each Compartment
for k = 1:size(Cfit,2)
ypred = Cfit_mtx(:,k);
SSE = sum((c(:,k)-ypred).^2);
SST = sum((c(:,k)-mean(c(:,k))).^2);
Rsq(k) = 1 - (SSE/SST);
fprintf('\t\tR² c(%d) = %7.4f\n',k, Rsq(k))
end
end
When I plot the figure, I want to have a legend that shows both the data points and the best fit lines but i am only able to show one or the other.
Can anyone help me? Thanks.

Answers (1)

Star Strider
Star Strider on 3 Feb 2021
The way I originally wrote that code, the points and the best fit lines all appeared (subsequent revisions had the data and line colours the same, not present in the original). See if using a different marker (other than '.') will show the data.
That all worked correctly in the code I originally wrote for you about three weeks ago in Predicting the kinetic constant of a reaction based on experimental data (attached here again).

Tags

Products

Community Treasure Hunt

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

Start Hunting!