- Use a suitable title for the thread subject and
- Do NOT use contributor names for tags.
How to write this loop?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
I have an array
[ 1.1 0.5 1.8 2.5 0.6 2.0 3.1 3.3 3.5 4.0 4.2 4.7 5.0 4.2 2.2 3.2 3.4 3.5 3.3 4.8 1.11 2.0 2.5]
start a loop from i=10 backward to i=2, if i is greater than any of j, j is from i-1 to i=1, then pick this i, close the loop. start another loop from i=11 to i=22, if i is greater than j, j is from i+1 to i=23, then pick this i, close the loop.
This is another way to explain the problem, starting from the first number in the array (1.1) to 4.0 which is the 10th element I want select number incrementally then end the loop there. Start another loop from the other end 2.5 ( the 23rd element ) incrementally back to the 11th element (4.0). the expected outcome is [1.1 1.8 2.5 3.1 3.3 3.5 4.0 5.0 4.8 2.5]
8 Commenti
dpb
il 16 Ago 2017
Modificato: dpb
il 16 Ago 2017
It also isn't defined clearly what to do when the nth value isn't greater than the (n-1)th. What happens for those conditions; is the lesser selected or the positions skipped so the resulting vector will have fewer than N/2 (N=10 here, the size of the subset input)?
I've got other commitment at the moment so can't take the time to try to guess what the intent is enough to actually write a solution making assumptions about what is the intent, but look at
doc diff
doc sign
doc arrayfun
with an anonymous function...
N=10; % your breakpoint location
dx=[0 diff(x(1:N)); % successive differences of the input
ix=sign(dx)>0); % logical addressing vector for x(i+1)>x(i)
Now the only question is which of x(ix) are the ones you actually want to end up with--that is just not yet clear enough to write the selection criterion.
Obviously the same idea works for the other section with reverse sign (or fliplr the subsection and it's identical to the first half).
Risposte (1)
mizuki
il 15 Ago 2017
for i = 10:-1:2
end
This means i changes from 10 to 2 with an interval -1.
I did not get the first part of your question, but for the second part, "If i is greater than j, j is from i+1 to i=23," write code as:
if(i > j)
for j = i+1:23
end
end
2 Commenti
mizuki
il 15 Ago 2017
Did you see my answer and run your code? A forward loop from 1 to 10 with interval 2 is
i = 1:2:10
<write your operation>
end
A backward loop from 10 to 1 with interval 2 is
for i = 10:-2:1
<write your operation>
end
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!