How can I check in an arbitrary vector that the first index is greater than the next index and so on?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
I'm thinking that I can make a for lp that runs through the length of the input vector and checks if the max is greater than the minimum for each index. Then make a new vector with only the inversions and finally take the length of that vector. I have this written this code so far:
function inv = inversions(board)
% Input vector
BR = [15 2 1 12 8 5 6 11 4 9 10 7 3 14 13];
L = length(BR);
for i = 1:L
if max(BR(i)) > min(BR(i))
inv
end
1 Commento
Adam
il 26 Giu 2019
Modificato: Adam
il 26 Giu 2019
You need to check each value against the preceeding value. BR(i) is a scalar so its min and max are both equal to the value itself and will not tell you anything about the sequence of numbers.
You also need to keep a running counter of cases where there is an inversion, which you would initialise to 0 before any loop.
Risposte (2)
Jan
il 26 Giu 2019
Modificato: Jan
il 26 Giu 2019
BR = [15 2 1 12 8 5 6 11 4 9 10 7 3 14 13]
Now you want to determine, if an element is larger or smaller than the former one:
BR(2:end) > BR(1:end-1)
Or alternatively:
diff(BR) > 0
Now you get a sequence of TRUE and FALSE values, which are treated as 1 and 0 such that a sum command counts them.
0 Commenti
Omer Badreldin
il 26 Giu 2019
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!