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
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
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.
0 件のコメント
Omer Badreldin
2019 年 6 月 26 日
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!