Index exceeds the number of array elements

5 次查看(过去 30 天)
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 个评论
Cris LaPierre
Cris LaPierre 2023-10-9
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

请先登录,再进行评论。

回答(1 个)

Cris LaPierre
Cris LaPierre 2023-10-9
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.

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by