if inside of for loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Alejandro Estudillo
am 19 Feb. 2018
Kommentiert: Jan
am 20 Feb. 2018
I don't know what is wrong with this code. The code works when I don't include the if statement. Any idea?
for i = 1:3
if rt > 100 & rt < 1000
average(i) = mean(rt(cue==i))
dev(i) = std(rt(cue==i))
end
end
1 Kommentar
the cyclist
am 19 Feb. 2018
You are leaving too much for us to guess at, which makes it difficult for us to help you.
Please describe what you mean by "doesn't work" in more detail. Does the code give an error? If so, tell us the complete error message, and which line it occurs on.
If it does not give an error, but just an unexpected result, tell us the expected and actual result.
In general, it would be better to supply code that we can actually run ourselves (e.g. by supplying the values of rt and cue.)
Akzeptierte Antwort
Jan
am 19 Feb. 2018
Bearbeitet: Jan
am 20 Feb. 2018
Or perhaps:
match = (rt > 100 & rt < 1000);
rtx = rt(match);
cuex = cue(match);
for i = 1:3
average(i) = mean(rtx(cuex==i))
dev(i) = std(rtx(cuex==i))
end
Note that "if rt > 100 & rt < 1000" is evaluated as:
if all(rt > 100 & rt < 1000) && ~isempty(rt)
2 Kommentare
Alejandro Estudillo
am 20 Feb. 2018
Bearbeitet: Alejandro Estudillo
am 20 Feb. 2018
Jan
am 20 Feb. 2018
@Alejandro: Yes, this way a typo. Inside the loop rtx and cuex are needed. I've fixed this in my answer.
Weitere Antworten (1)
Birdman
am 19 Feb. 2018
Bearbeitet: Birdman
am 19 Feb. 2018
You probably forgot subscripting of rt.
for i = 1:3
if rt(i) > 100 & rt(i) < 1000
average(i) = mean(rt(cue==i))
dev(i) = std(rt(cue==i))
end
end
2 Kommentare
Birdman
am 20 Feb. 2018
But again
rt(cue==i)
this will result in an array. You may perhaps do it before the loop and give it subscripted to for loop as
rt=rt(cue==i);
for i=1:3
if rt(i)...
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements 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!