Index exceeds the number of array elements

4 vues (au cours des 30 derniers jours)
James Atwell
James Atwell le 9 Oct 2023
function Q32(x2,y2)
%aim of function to have two vectors x, y and each has a size of m. Order the vectors according to value (max 1st, lowest last) %Make a (m x m) matrix, where the diagonal terms have the Max values of vector x and the all other matrix elements have the Max %value of y.
x2 = x2(sort(x2, 'descend'));
y2 = y2(sort(y2, 'descend'));
lengx2 = length(x2);
lengy2 = length(y2);
n = lengy2;
for x = 1:1:lengx2
for y = 1:1:lengy2
if x==y
M(x,y) = x2(1);
else
M(x,y) = y2(1);
end
end
M(x,n) = x2(1);
n = n-1;
if n == 0
break
end
end
disp(M);
end
%This is my function and then i tried using it for these vectors
x2 = (1:1:8);
y2 = (1:2:16)';
Q32(x2,y2)
%the error reads
Index exceeds the number of array elements. Index must not
exceed 8.
Error in Q32 (line 3)
y2 = y2(sort(y2, 'descend'));
Error in testing (line 4)
Q32(x2,y2)
  1 commentaire
Cris LaPierre
Cris LaPierre le 9 Oct 2023
Recreating the issue:
x2 = (1:1:8);
y2 = (1:2:16)';
Q32(x2,y2)
Index exceeds the number of array elements. Index must not exceed 8.

Error in solution>Q32 (line 8)
y2 = y2(sort(y2, 'descend'));
function Q32(x2,y2)
%aim of function to have two vectors x, y and each has a size of m. Order the vectors according to value (max 1st, lowest last) %Make a (m x m) matrix, where the diagonal terms have the Max values of vector x and the all other matrix elements have the Max %value of y.
x2 = x2(sort(x2, 'descend'));
y2 = y2(sort(y2, 'descend'));
lengx2 = length(x2);
lengy2 = length(y2);
n = lengy2;
for x = 1:1:lengx2
for y = 1:1:lengy2
if x==y
M(x,y) = x2(1);
else
M(x,y) = y2(1);
end
end
M(x,n) = x2(1);
n = n-1;
if n == 0
break
end
end
disp(M);
end

Connectez-vous pour commenter.

Réponses (1)

Cris LaPierre
Cris LaPierre le 9 Oct 2023
Your code is using the sorted values of y2 to index into y2. However, y2 only has 8 elements, but your values of y2 go up to 15. There error is because your index number cannot be higher than the number of elements in the vector.
y2 = (1:2:16)
y2 = 1×8
1 3 5 7 9 11 13 15
% works
y2(5)
ans = 9
% your error
y2(15)
Index exceeds the number of array elements. Index must not exceed 8.

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Produits


Version

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by