Index exceeds the number of array elements
    4 visualizzazioni (ultimi 30 giorni)
  
       Mostra commenti meno recenti
    
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 Commento
  Cris LaPierre
    
      
 il 9 Ott 2023
				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
Risposte (1)
  Cris LaPierre
    
      
 il 9 Ott 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)
% works
y2(5)
% your error
y2(15)
0 Commenti
Vedere anche
Categorie
				Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!