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 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
BAILEY MCMASTER
am 25 Sep. 2023
Kommentiert: Walter Roberson
am 25 Sep. 2023
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 Kommentare
Akzeptierte Antwort
Star Strider
am 25 Sep. 2023
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 Kommentare
Weitere Antworten (1)
Walter Roberson
am 25 Sep. 2023
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 Kommentar
Walter Roberson
am 25 Sep. 2023
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?
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!