Does my for looop make sense?

Here is the equation I am using in the code below. I am using a nested for loop. I want to see the value of c(t) when R has two different values, and also when A has 5 differnt values, and then thus plot the data.
for t, I am using linespace.
Can anyone confirm please if my code make sense? I think I have coded the for loop correctly, but i am not entiry sure.
clc, clear all, close all
% two values for R
R = [10 30];
% 5 vaules for a
a = [0.1 0.2 0.5 0.75 1];
% t for time
t = linspace(0,10,100);
hold on
for i = 1:2
for j = 1:length(a)
ct = R(i)-R(i)*(exp(-a(j)*t));
plot(t,ct)
text(max(t)/2,max(ct),num2str(a(i)))
end
end

 Accepted Answer

The loops make sense, and the lines look good.
The texts could use some adjustment in two aspects:
1) Note that the text labels are specified as a(i), but they should be a(j).
2) The positions of the texts should be adjusted to show more clearly which line each text corresponds to. For the x-coordinate you are using max(t)/2, which is ok (though this value can be computed before the loops since it doesn't depend on i or j). For the y-coordinate, you are using max(ct), the maximum value of the curve, which means that the texts corresponding to curves with low a values are quite a bit above their curves. You can use the middle ct value instead, to get each text on top of its curve (but even then some of them overlap), which would look something like this:
clc, clear all, close all
% two values for R
R = [10 30];
% 5 vaules for a
a = [0.1 0.2 0.5 0.75 1];
% t for time
t = linspace(0,10,100);
text_x = max(t)/2;
hold on
for i = 1:2
for j = 1:length(a)
ct = R(i)-R(i)*(exp(-a(j)*t));
plot(t,ct)
text(text_x,ct(round(end/2)),num2str(a(j)))
end
end
The code does what it's supposed to do, I think, but you may want to do further fine-tuning of those text positions.

More Answers (1)

Torsten
Torsten on 19 Dec 2021
Edited: Torsten on 19 Dec 2021
for i = 1:numel(R)
for j = 1:numel(a)
ct(i,j,:) = R(i)*(1-exp(-a(j)*t));
end
end
plot(t,ct(1,1,:)) % plot curve for R = 10 and a = 0.1

Categories

Tags

Community Treasure Hunt

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

Start Hunting!