Index exceeds the number of array elements

조회 수: 4 (최근 30일)
James Atwell
James Atwell 2023년 10월 9일
답변: Cris LaPierre 2023년 10월 9일
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