How can I repeat a cycle in a for loop with n samples
Show older comments
for n=1:N
if t>=Tc
t=0;
end
if t<Ti
Pmus(n)=A*(t/Ti);
Pm(n)=5;
else
Pmus(n)=A*(exp(-4*(t-Ti)/Te)-exp(-4))/(1-exp(-4));
Pm(n)=0;
end
t=t+1;
end
I have to simulate the muscular pressure in a lung, which has the function A*(t/Ti) for when t is smaller than the inspiratory time and the other function for when t is larger than the inspiratory time (but smaller than the inspiratory and expiratory time combined). After t has reached Tc(=Ti+Te), I want the cycle to start anew, but how do I do that, when I have a set number of samples (I need those in another function as well)?
4 Comments
Birdman
on 13 Mar 2018
Is this your entire code? If not, can you share your entire code?
Lotte Vermeulen
on 13 Mar 2018
Birdman
on 13 Mar 2018
Undefined function or variable 't'.
Lotte Vermeulen
on 13 Mar 2018
Answers (2)
Guillaume
on 13 Mar 2018
I'm not entirely clear on what you're asking. As it is your code can be simplified to:
%no loop needed
Pmus = [A*((0:Ti-1)/Ti), A*(exp(-4*(0:Tc-Ti-1)/Te) - exp(-4)) / (1-exp(-4))];
Pm = [5*ones(1, Ti), zeros(1, Tc-Ti)];
If you want to repeat that for several cycles:
Pmus = repmat(Pmus, 1, numcycles);
Pm = repmat(Pm, 1, numcycles);
2 Comments
Lotte Vermeulen
on 13 Mar 2018
The way you wrote your original code, it would only have worked if Ti, Tc, and Te were integers much greater than 1, as your time step was 1. So I went with that assumption.
Never mind, it's easily modified for non-integer time steps, smaller than 1. Again, there really is no need for loop. All you do is create a vector of time steps with as many steps as you want:
A=5;
Ti=1.67; %De inspiratietijd in s
Te=3.33; %De expiratietijd in s
Tc = Ti + Te; %safer than hardcoding the value
numsteps = 100; %for example
t = linspace(0, Tc, numsteps);
Pmus and Pm can then be calculated in just one line each:
Pmus = [A*t(t<Ti)/Ti, A*(exp(-4*(t(t>=Ti)-Ti)/Te) - exp(-4)) / (1-exp(-4))];
Pm = [5*ones(1, sum(t<Ti)), zeros(1, sum(t>=Ti))];
plot(t, [Pmus; Pm]);
You can of course repeat that for how many cycles you want, using repmat:
numrepeat = 5;
trepeat = reshape(t' + (0:numrepeat-1) * t(end), 1, []); %requires R2016b or later
Pmusrepeat = repmat(Pmus, 1, numrepeat);
Pmrepeat = repmat(Pm, 1, numrepeat);
plot(trepeat, [Pmusrepeat; Pmrepeat]);
edit: it looks like Ts is your sampling period. In that case, instead of using linpace to build the t vector use the colon operator:
t = 0:Ts:Tc;
The rest is still the same.
Torsten
on 13 Mar 2018
t=Tstart;
n=1;
cycle=1;
flag=0;
while flag==0
if t<Ti
Pmus(n,cycle)=A*(t/Ti);
Pm(n,cycle)=5;
else
Pmus(n,cycle)=A*(exp(-4*(t-Ti)/Te)-exp(-4))/(1-exp(-4));
Pm(n,cycle)=0;
end
t=t+Ts;
n=n+1;
if t>Tf
cycle=cycle+1;
n=1;
t=Tstart;
end
end
Categories
Find more on Loops and Conditional Statements 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!