Cannot find error in my sort function
조회 수: 6 (최근 30일)
이전 댓글 표시
So my code is supposed to work so for an input array, findSortedMatches sorts the array and looks for rows that didn’t move. It returns the number of rows that didn’t move (matches) and an array of the rows that didn’t move (matched rows).
Code
function [matches, matched_rows] = findSortedMatches(score)
score = [N,2];
matches = 0;
matched_rows = [];
[~, sorted] = sortdata(score);
next_unsorted = make_nextRow(score,1);
next_sorted = make_nextRow(sortdata,1);
for i = 1:size(score,2)
unsorted = next_unsorted;
if all(unsorted==next_sorted)
next_sorted() matches unsorted
matches = matches + 1;
matched_rows = [matched_rows; unsorted];
end
end
end
function [data_sortbyscore, bestscore_id] = sortdata( score )
[~, idx] = sort(score(:, 2));
data_sortbyscore = score(idx, :);
bestscore_id = data_sortbyscore(end, 1);
end
Test Case and Expected Answers
>> scores = [20,90;13,56;3,67;10,78;2,54];
>> [num_matches, row_matches] = findSortedMatches(scores)
num_matches =
3
row_matches =
13 56
3 67
10 78
>>
>>
>> array = [2 34; 5 67];
>> [num_matches, matched_rows]=findSortedMatches(array)
num_matches =
2
matched_rows =
2 34
5 67
>> array = [5 67; 2 34];
>> [num_matches, matched_rows]=findSortedMatches(array)
num_matches =
0
matched_rows =
[]
댓글 수: 0
채택된 답변
Matt Fig
2012년 10월 16일
There is no way you are calling the function you post without getting errors. For one thing, you reference a variable N on the first line that does not exist in that function. On that same line you destroy the input argument so that no matter what you pass in the function should return the same result. Next, you have what is apparently and uncommented comment
next_sorted() matches unsorted
in the IF statement that will cause an error.
So what function really produced those results?
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!