How can I check in an arbitrary vector that the first index is greater than the next index and so on?
1 view (last 30 days)
Show older comments
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 Comment
Adam
on 26 Jun 2019
Edited: Adam
on 26 Jun 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.
Answers (2)
Jan
on 26 Jun 2019
Edited: Jan
on 26 Jun 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 Comments
Omer Badreldin
on 26 Jun 2019
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!