index error,exceeding array dimensions.
2 次查看(过去 30 天)
显示 更早的评论
Hello Everyone,
I'm here to ask if there is anyone who can help me see where i am doing wrong because i really cannot see what i keep writing that is not accepted by the program
it gives out an error of exceeding index but i see no mistake in the input of the functions and the limits that the index has to run (from 1 until dim i.e)
what is confusing is the fact that it sometimes gives no mistake but lately the same writings have always gotten denied
function [Vet_ord] = ordina(Vet,dim)
for i=1:dim
k=i;
j=i+1;
while j<dim
if Vet(k)>Vet(j)
k=j;
end
j=j+1;
end
if i~=k
temp=Vet(i);
Vet(i)=Vet(k);
Vet(k)=temp;
end
Vet_ord=vet;
end
end
the warning is : index exceeds the number of array elements.
Index must not exceed 1.
Error in ordina (line 6)
if Vet(k)>Vet(j)
thanks everyone in advance for the help.
5 个评论
Dyuman Joshi
2023-1-27
@savino cataleta is the value of Dim calculated from Vet or manually inputted?
If the former, why use it as an input when you can obtain the value in the code directly using inbuilt functions.
If the latter, you have to check that Dim and any other variables used in reference to Dim do not exceed the size of Vet.
回答(1 个)
Sulaymon Eshkabilov
2023-1-27
Here is the corrected code:
Vet = randi([-9,9], 1, 7);
dim = numel(Vet)+1;
V = ordina(Vet,dim)
function Vet_ord = ordina(Vet,dim)
for i=1:dim-1 % Excess the dimension of Vet
k=i;
j=i+1;
while j<dim-1 % Excess the dimension of Vet
if Vet(k)>Vet(j)
k=j;
end
j=j+1;
end
if i~=k
temp=Vet(i);
Vet(i)=Vet(k);
Vet(k)=temp;
end
Vet_ord=Vet; % The variable name has to be Vet not vet
end
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!