Index exceeds the number of array elements(3)

3 次查看(过去 30 天)
For a matrix
A=[4 1 3 1;1 4 1 3;3 1 4 1;1 3 1 4]
[L,P,D]=eigen(A);
I have a function:
function [L,P,D]=eigen(A)
format
[~,n]=size(A);
P=[];
D=[];
L=eig(A);
L=transpose(L);
L=real(L);
L=sort(L);
for i= 1:n-1
Temp1 = L(i);
Temp2 = L(i+1);
if closetozeroroundoff(Temp1-Temp2, 7)== 0
L(1,i+1) = L(1, i);
end
end
if rank(L) ~= n
L = closetozeroroundoff(L,7);
end
fprintf('all eigenvalues of A are\n')
display(L)
M = unique(L);
M = transpose(M);
display(M)
m = groupcounts(transpose(L));
display(m)
for i = 1:n
fprintf('eigenvalue %d has multiplicity %i\n',M(i),m(i))
end
and I get the error that Index exceeds the number of array elements(3) even though it prints each eigenvalue with its multiplicity. Any ideas on how to fix it?
M is the eigenvalues that are unique
L is the list of all the eigenvalues (even the repeated ones)
m is the number of times each value in L appears in M

回答(1 个)

Cris LaPierre
Cris LaPierre 2021-4-16
We can't run your code. We need your closetozeroroundoff function.
However, the error message isn't about whether or not there are 3 eigen values. It is that you are trying to index a variable that only has 3 values with an index that is greater than 3.
% Create an array with 3 elements
num = [1,2,3];
% Works
num(2)
ans = 2
% Error because 5>length(num)
num(5)
Index exceeds the number of array elements (3).

类别

Help CenterFile Exchange 中查找有关 Linear Algebra 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by