Adding a varying value to a for-loop
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
KSSV
2017-3-31
编辑:KSSV
2017-3-31
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 个评论
KSSV
2017-3-31
Yes..you can avoid for loops...nby vector arithmetic. And Thanks is accepting the answer. :)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!