Index exceeds the number of array elements (6)
1 view (last 30 days)
Show older comments
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
Star Strider
on 22 May 2019
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.
Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!