Azzera filtri
Azzera filtri

Adding a varying value to a for-loop

3 visualizzazioni (ultimi 30 giorni)
Chris Matthews
Chris Matthews il 31 Mar 2017
Commentato: KSSV il 31 Mar 2017
I have a function that has some constant and some varying inputs.
t=0.2; %constant
NT =300; %constant
ti = 1:NT;
B = exp(-5*t); %constant
A = 1-exp(-5.*t); %constant
pinit = 0.242; %initial p value
r = ones(1,NT); %input step constant througout, gives vector
%_________________________________________
for k = 1:NT
if k<=11
c1(k) = 0;
else
c1(k) = (B*c1(k-1)) - (pinit*c1(k-11))*(A) + (pinit*r(k-11))*(A);
end
end
The varying values are as follows: The r input is a 1x300 vector, all 1's. The ti input is a 1x300 vector, over time.
and gives an output of c(t), a 1x300 vector from the eqn.
I now want to change pinit from a contant, set at 0.242 to a range of values [0:0.01:2.99] however, when I change it, I get the error that the c(t) output must have the same dimensions as the eqn, which I understand, but I thought by setting P to have a 1x300 matrix, this would work.
Can someone please help me modify my code so that pinit is a varying value?

Risposta accettata

KSSV
KSSV il 31 Mar 2017
Modificato: KSSV il 31 Mar 2017
t=0.2; %constant
NT =300; %constant
ti = 1:NT;
B = exp(-5*t); %constant
A = 1-exp(-5.*t); %constant
% pinit = 0.242; %initial p value
pinit = [0:0.01:2.99]; %initial p value
r = ones(1,NT); %input step constant througout, gives vector
%_________________________________________
c1 = zeros(length(pinit),length(NT)) ;
for i = 1:length(pinit)
for k = 1:NT
if k<=11
c1(i,k) = 0;
else
c1(i,k) = (B*c1(i,k-1)) - (pinit(i)*c1(i,k-11))*(A) + (pinit(i)*r(k-11))*(A);
end
end
end
Note that the above can be vectorized.....as you are beginner...I suggest you to run from loops and then go to vectorizing this.
  2 Commenti
Chris Matthews
Chris Matthews il 31 Mar 2017
Modificato: Chris Matthews il 31 Mar 2017
Sorry, I'm not sure what you mean. Does that mean I can calculate c(t) using only vector arithmetic rather than a for-loop?
But thanks for the code addition, works like I wanted it to. Have a good arvo.
KSSV
KSSV il 31 Mar 2017
Yes..you can avoid for loops...nby vector arithmetic. And Thanks is accepting the answer. :)

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by