Index exceeds the number of array elements
조회 수: 4 (최근 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
2023년 10월 9일
Recreating the issue:
x2 = (1:1:8);
y2 = (1:2:16)';
Q32(x2,y2)
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
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)
% works
y2(5)
% your error
y2(15)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!