I'm trying to make a for loop that has if statments that use the increments from my i to run them. How can I make this work, it won't run.
조회 수: 1 (최근 30일)
이전 댓글 표시
Ts=30; % ms
Td=60; % ms
sc=10^-3; % conversion from ms to s
Chs=.001; % L/mmhg
Chd=.015; % L/mmhg
dt=.1; % incrment of time
N=800; % number of elements
time=0:.1:80; % all time values together
for i=0:N
if i==0:99
Ch(i+1)=(Chs-Chd)*exp(-dt/Td)+Chd;
elseif i==100:349;
Ch(i+1)=(Chs-Chd)*exp(-dt/Td)+Chd;
end
end
댓글 수: 0
채택된 답변
Star Strider
2023년 9월 25일
Try this —
Ts=30; % ms
Td=60; % ms
sc=10^-3; % conversion from ms to s
Chs=.001; % L/mmhg
Chd=.015; % L/mmhg
dt=.1; % incrment of time
N=800; % number of elements
time=0:.1:80; % all time values together
for i=0:N
if any(i==0:99)
Ch(i+1)=(Chs-Chd)*exp(-dt/Td)+Chd;
elseif any(i==100:349)
Ch(i+1)=(Chs-Chd)*exp(-dt/Td)+Chd;
end
end
Ch
.
댓글 수: 0
추가 답변 (1개)
Walter Roberson
2023년 9월 25일
if i==0:99
The right-hand side of that == is a vector containing [0, 1, 2, 3, ... 99]
The == is comparing the current value of the scalar in i to the entire vector. As i only has a single value in it, there can be at most one value in the integer range 0 to 99 that i is equal to, so the result of the comparison is either a vector of 100 false values or else is a vector that has 99 false values and one true value somewhere in it.
When you have an if statement that is testing a vector, MATLAB interprets the test as being true only if all the values being tested are non-zero. So the test is equivalent to
if all((i==0:99)~=0)
but we can guarantee that at the very least one value is going to be false, so we can be sure that the test will fail.
If you had written:
if any(i==0:99)
then that could potentially work. It would not be the recommended way to write such code, but it could work.
Better would be:
if i >=0 & i <= 99
but you could also take advantage of the fact that i is never negative to code
if i <= 99
stuff
elseif i <= 349
stuff
end
댓글 수: 1
Walter Roberson
2023년 9월 25일
Ch(i+1)=(Chs-Chd)*exp(-dt/Td)+Chd;
elseif i==100:349;
Ch(i+1)=(Chs-Chd)*exp(-dt/Td)+Chd;
What is the difference in the calculations? What are you doing differently between the two cases? What is the reason to have two different cases?
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!