Binjo1
Binjo1

Reputation: 43

Matlab: i=2, if B(i)>B(i+1)... Subscript index error, must be positive integer

I'm writing a sorting algorithm for class and this error came up for line 14, Subscript indices must either be real positive integers or logicals. I searched for the answer in different threads but the answers seemed confusing and not really relevant to my problem. I understand the meaning of the error but I don't get why my code is failing. i=2 is a positive integer, there's no division or multiplication by non integers or negative integers, there's no zero in the place of the subscript index as far as I can tell. I don't get it. Thanks in advance for any help!

function bubblesort(A)
%bubble sorting algo
B=A;
c=numel(B);
%count the number of elements in a, store it as c
if B(1)>B(2)
    left=B(1);
    right=B(2);
    B(1)=right;
    B(2)=left;
end
i=2;
while i+1<=c
    **if B(i)>B(i+1)**
        left=B(i);
        right=B(i+1);
        B(i)=right;
        B(i+1)=left;
        i=i-1;
    else
        i=i+1;
    end
end
B
end

Upvotes: 0

Views: 51

Answers (1)

Jorge P&#233;rez
Jorge P&#233;rez

Reputation: 96

The problem is that (unless the first element of A is already the smallest) the i = i-1 line will make i = 0 for the smallest element and the code will fail. I think that the function can be fixed adding if i>1.

function bubblesort(A)
%bubble sorting algo
B = A;
c = numel(B);
%count the number of elements in a, store it as c  

i = 1;
while i+1 <= c
    if B(i) > B(i+1)
        left = B(i);
        right = B(i+1);
        B(i) = right;
        B(i+1) = left;
        if i > 1
            i = i-1;
        end
    else
        i = i+1;
    end
end
B
end

Upvotes: 1

Related Questions