MATLAB: Plotting graph with for loop

for loop

Hi I'm new to matlab

Best Answer

You actually wrote vectorized code, so you don’t need a loop:
Co = 70;
W1 = 120;
W2 = 200;
M1 = W1 / 2.204623;
M2 = W2 / 2.204623;
fprintf('T\tC1\tC2\n');
t = 0:0.1:5;
C1 = Co * exp((-30 * t)./ M1);
C2 = Co * exp((-30 * t)./ M2);
fprintf('%g\t%g\t%g\n', [t, C1, C2]')
plot(t, C1, 'r', t, C2, 'g');
xlabel('Time (minutes)')
ylabel('Insulin Concentration (m\itM\rm)')
If you absolutely must use a loop, subscript the appropriate variables, here ‘t’, ‘C1’ and ‘C2’:
t = 0:0.1:5;
for k1 = 1:length(t)
C1(k1) = Co * exp((-30 * t(k1))./ M1);
C2(k1) = Co * exp((-30 * t(k1))./ M2);
end
fprintf('%g\t%g\t%g\n', [t, C1, C2]')
plot(t, C1, 'r', t, C2, 'g');
xlabel('Time (minutes)')
ylabel('Insulin Concentration (m\itM\rm)')