using break to stop nested loop

X = [1 2 3 4 5 4 3 6 7 8 9 10 11 12 11 10 9 8 7 8 9 10 9 8 7 6 5 4 3 2 1 2 4 5 6 7 8 9 11 12 11 10 9 8 7 9 10 9 8 7 6 5 4 3 2 1];
I want to take out vectors which start when value greater than 2 and end value end less than 11. The resulting vectors will be [3 4 5 4 3 6 7 8 9 10 ] and [4 5 6 7 8 9], which will be kept in cell array.
The current code I tried saved only [4 5 6 7 8 9] in fwd cell array.
Could anyone please help me to save both vectors in the cell array? thank you.
clc; clear; close all
X = [1 2 3 4 5 4 3 6 7 8 9 10 11 12 11 10 9 8 7 8 9 10 9 8 7 6 5 4 3 2 1 1 2 4 5 6 7 8 9 11 12 11 10 9 8 7 9 10 9 8 7 6 5 4 3 2 1];
start = min(X)+2;
ed = max(X) -2;
m = length(X);
f = 1;
i = 2;
while i < m
k=1;
if X(i) >= start && X(i-1) <= start && X(i+1) > X(i)
a(k) = X(i);
for j = i+1:m-1
if X(j+1) > ed && X(j+2) >= X(j+1) && X(j) < X(j+1)
b (k) = X(j);
fwd{k} = [X(i):X(j)];
if ~isempty(b(k))
break;
end
end
end
i =j+1;
k =k+1;
else
i = i+1;
end
end

3 Kommentare

Stephen23
Stephen23 am 22 Mai 2020
Bearbeitet: Stephen23 am 22 Mai 2020
Yu Zhi: your problem is not sufficiently defined. For example, here are two sequences that meet your requirement "start when value greater than 2 and end value end less than 11", why are they not included in the output?:
7 8 9 10
8 7 9 10
What about ther prefectly good sequence
8
which also fulfills your conditions? Why is that sequence not in your output?
HYZ
HYZ am 22 Mai 2020
Actually I am simulating a situation that an animal leaves one end and enter the other end as in the diagram.
I somehow changed the postion of k and got what I want. But honestly, I still don't really understand how putting k=1; k=k+1; can make it work.
clc; clear; close all
X = [1 2 3 4 5 4 3 6 7 8 9 10 11 12 11 10 9 8 7 8 9 10 9 8 7 6 5 4 3 2 1 1 2 4 5 6 7 8 9 11 12 11 10 9 8 7 9 10 9 8 7 6 5 4 3 2 1];
start = min(X)+10;
ed = max(X) -10;
m = length(X);
i = 2;
k=1;
while i < m
if X(i) >= start && X(i-1) <= start && X(i+1) > X(i)
a(k) = X(i);
for j = i+1:m-1
if X(j+1) > ed && X(j+2) >= X(j+1) && X(j) < X(j+1)
b (k) = X(j);
fwd{k} = [X(i):X(j)];
if ~isempty(b(k))
k=k+1;
break;
end
end
end
i =j+1;
else
i = i+1;
end
end
fwd;
HYZ
HYZ am 22 Mai 2020
7 8 9 10 and 8 7 9 10 are not starting points of the track. the starting point is the first value which came after 2. the end is the last value which comes just before 9.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

HYZ
am 22 Mai 2020

Kommentiert:

HYZ
am 22 Mai 2020

Community Treasure Hunt

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

Start Hunting!

Translated by