length(b) of a 2D array is defined as
length = max(size(b)) otherwise
You should avoid using length() for anything that might be a matrix, as you do not know whether the size returned refers to rows or columns.
B is the augmented matrix. Typically it would have multiple rows; it will have multiple columns unless a and b are both empty or one of them is empty and the other has only a single column.
B=sortrows(B(j:n),'descend');
You are using a single index for B. If B is 2D or B is a column vector then the result would be a column vector; if B happens to be a row vector (because a and b both have exactly one row) then B(j:n) would be a row vector. Either way it seems unlikely that sortrows() is the desired operation on what is either a row or column vector.
Notice that B(j:n) would be a subset of B. So each time through your for j loop, B is going to be getting smaller -- faster than you would expect. The first time through, you would be taking B(1:n), which would be length n. The second time through you would be taking B(2:n) which would give you a vector of length n-1 and that replaces B. The third time through you would take B(3:n) -- but B refers to the B that has already had B(1) removed in the previous iteration, so B(3:n) would correspond to what was originally B(4:n). The next time through, j=4, B(4:n) but that is relative to the B created in the pervious iteration, so it would be B(8:n) relative to the original matrix...
I would suggest to you that the B(j:n), if it were correct at all, should be referring to the original B, not to the output of the sortrows() of the partial B.
Perhaps you want to sortrows() based upon columns j to n -- which is something that you can do with sortrows()