MATLAB Answers

0

Index exceeds the number of array elements (6)

Asked by Alessandro Marutti on 22 May 2019
Latest activity Commented on by Alessandro Marutti on 22 May 2019
Hi guys, I know there're some similar questions around the comunity but I didn't find an answer to understand my problem.
I'm writing a code to sort an vector without using "sort" function, however matlab returns me an error that tells :"Index exceeds the number of array elements (6); min = q(s);". I put "min" equal to the element of vector "q" with index "s" so I don't understand why matlab tells me this error.
I hope you can help me, thanks.
q = [3 1 -1 4 2 0 ]
qRiserva = 0; % variable to temporarily keep the element of q(s)
s = 1; % index for outer 'for cycle'
min = q(s);
max = q(1);
i = 1; % index for deeper 'for cycle'
for s = s :length(q)
for i = s: length(q)
if q(i) <= min
qRiserva(s) = q(s)
min = q(i)
q(s) = min
q(i) = qRiserva(s)
end
end
s = s+1;
min = q(s);
end

  7 Comments

OK thanks guys, now it doesn't show me the error but the code doesn't work either.
If I write the code as a 6-times sequence of the deeper "for loop" it works but if I write the code as in the first message (inside another "for") it doesn't work
You are apparently writing a °bubble sort’ algorithm. The essence of that is to compare adjacent elements, and then switch their order (depending on whether you are sorting in the ascending or descending mode), keeping track of the number of switches in each iteration. Keep doing that until there are no more switches.
I moved "min = q(2)" (to whom I changed name) from the bottom to the top between the two "for loops" and now everything works right.
Thanks a lot to everybody your're super efficient!

Sign in to comment.

0 Answers