How can I check in an arbitrary vector that the first index is greater than the next index and so on?

1 vue (au cours des 30 derniers jours)
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 commentaire
Adam
Adam le 26 Juin 2019
Modifié(e) : Adam le 26 Juin 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.

Connectez-vous pour commenter.

Réponses (2)

Jan
Jan le 26 Juin 2019
Modifié(e) : Jan le 26 Juin 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.

Omer Badreldin
Omer Badreldin le 26 Juin 2019
Thanks guys! I worked it out :-)
I did this:
function inv = inversions(board)
% Input vector (test case)
% board = [15 2 1 12 8 5 6 11 4 9 10 7 3 14 13];
L = length(board);
i = 0;
inv = 0;
% L-1 because board(i+1) would give an index that exceeds the number of indices in board.
for i = 1:L-1
if board(i) > board(i+1) % if condition true, inv will be updated.
inv = inv+1;
end
i=i+1;
end
end
  1 commentaire
Jan
Jan le 26 Juin 2019
Modifié(e) : Jan le 26 Juin 2019
Do not increase the loop counter i manually inside the loop: omit the useless lines i=0 and i=i+1 .
More Matlab'ish solutions without a loop:
inv = sum(board(1:end-1) > board(2:end))
or
inv = sum(diff(board) < 0)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by