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

채택된 답변

Star Strider
Star Strider 2023년 9월 25일
It runs. For equalities such as you are using, use the any function.
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
Ch = 1×350
0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010 0.0010
.

추가 답변 (1개)

Walter Roberson
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
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 CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by