필터 지우기
필터 지우기

Adding a varying value to a for-loop

조회 수: 3 (최근 30일)
Chris Matthews
Chris Matthews 2017년 3월 31일
댓글: KSSV 2017년 3월 31일
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?

채택된 답변

KSSV
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
Chris Matthews
Chris Matthews 2017년 3월 31일
편집: Chris Matthews 2017년 3월 31일
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 2017년 3월 31일
Yes..you can avoid for loops...nby vector arithmetic. And Thanks is accepting the answer. :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by