我正在编写类别的分类算法,此错误是第14行出现的,下标索引必须是真正的正整数或逻辑。我在不同的线程中搜索了答案,但是答案似乎令人困惑,并且与我的问题无关。我了解错误的含义,但我不明白为什么我的代码失败。i = 2是一个积极的整数,没有非整数或负整数的划分或乘法,据我所知,在下标索引的位置没有零。我不明白。预先感谢您的任何帮助!
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
问题是(除非A的第一个元素已经是最小的(I = i-1行将使最小元素成为I = 0,并且代码将失败。我认为如果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