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