How to check the sort order of a vector
조회 수: 1 (최근 30일)
이전 댓글 표시
It is not working
b=[5 6;3 4;1 2]
[r,c]=size(b);
a=b(:,c);
if for i=1:r-1, a(i)>=a(i+1), end
disp 'OK', else disp 'Not OK',
end
댓글 수: 1
Stephen23
2017년 1월 18일
편집: Stephen23
2017년 1월 18일
"It is not working"
This code is not working because it has many bugs. It has many bugs because the way you are writing your code lets you write lots of bugs. Beginners often seem to write lots of code without checking it as they write it. Then they are surprised when the code does not run, and have no idea where the errors are in the large block of code. They are unable to cope, and they actually have no idea what their code is doing.
Writing lots of code does not mean that you have solved your task. Having lots of code does not mean that you have done good work. It is a waste of your time. You need to first understand how to implement your algorithm, write it, and test it as you write it. Write one line or operation, then test it. Check that it does exactly what you need it to do. Do not move on until it is correct. Then you will not end up with a huge collection of bugs like this code.
You also need to learn to pay attention to what the MATLAB editor is telling you. The editor shows you where bugs are, and where you can make your code better. Here is your code:
Look at all of the red underlining, and the red lines on the RHS of the editor: these tell you where code errors have been identified. MATLAB is helping you to write good code: why are you ignoring it?
When you learn how to check and debug your own code than you do not need to rely on coming to internet forums to make your code work. You could do it yourself.
You also need to learn to read the documentation. The documentation tells us all how to use MATLAB. It tells us how to call functions. It tells us what inputs and outputs functions have. Reading the documentation would help to understand that that this
if for
is not valid syntax.
To start to learn how to use MATLAB you should do the introductory tutorials:
And also read this:
채택된 답변
Guillaume
2017년 1월 18일
Please, do read Stephen's comment to your question above and follow his excellent advice.
The simple way to implement what I assume your code is supposed to be doing would be:
b = [5 6; 3 4; 1 2]
if all(diff(b(:, end)) <= 0)
disp('OK');
else
disp('Not OK');
end
Notes:
- the code above uses end to get the last column of b rather than spending querying the size and using that to index the last column
- the code uses diff to get the difference between consecutive values and all to check that they're all the same sign.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!