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

1 次查看(过去 30 天)
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 个评论
Adam
Adam 2019-6-26
编辑:Adam 2019-6-26
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.

请先登录,再进行评论。

回答(2 个)

Jan
Jan 2019-6-26
编辑:Jan 2019-6-26
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 2019-6-26
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 个评论
Jan
Jan 2019-6-26
编辑:Jan 2019-6-26
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)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by