views:

152

answers:

2

I'm writing an insertion sort in MATLAB. I called my function like this:

>> A = [5 4 3 2 1]

A =

     5     4     3     2     1

>> insertion_sort(A)

but when I run it I get the error

??? Attempt to reference field of non-structure array.

    Error in ==> insertion_sort at 6
        for j=2:original.length

Here's my original code:

function sorted = insertion_sort(original)

    for j=2:original.length
        key = original(j);
        i = j-1;
        while i > 0 && original(i) > key
            original(i+1) = original(i);
            i = i-1;
        end
        original(i+1) = key;
    end 

sorted = original;

end

Anyone know what I'm doing wrong?

+1  A: 

You want to use length(original) instead of original.length. Fundamental data types don't have a length method, so MATLAB mistakenly thinks you are trying to access a field named length in a structure, which original is not.

gnovice
+1  A: 

Try numel(original) instead of original.length. MatLab matrices are primitive types, not objects, and they don't have a length property.

Ben Voigt