Index exceeds the number of array elements(3)

3 views (last 30 days)
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
output:
That is intended to find the eigenvalues (L) and then checks how many times each unique eigenvalue (M) is repeated in L. But when I it, the groupcounts gives me an error, even though the output is correct, that says Index exceeds the number of array elements(3).
How do I fix it?

Answers (1)

Clayton Gotberg
Clayton Gotberg on 16 Apr 2021
The error
Index exceeds the number of array elements (3).
This means that you are asking for an element beyond the boundaries of one of your arrays, which has 3 elements.
The cause
If we zoom out to
for i = 1:n
fprintf('eigenvalue %d has multiplicity %i\n',M(i),m(i))
end
We see that there is one indexing variable, i, which is being used in M(i) and m(i). The for loop gives i values from 1 to n, which (from earlier) is the number of columns in your input matrix. Your input matrix is 4x4, so n = 4. When the program tries to use i = 4, it calls for M(4) and m(4), which do not exist because they are beyond the boundaries of those arrays.
You can see the program works as intended for i = 1:3, so the issue is that listing the eigenvalues with their multiplicities has changed the representation from 4 eigenvalues (allowing the possibility of duplicates) to 3 eigenvalues (removing duplicates).
The solution
When you have determined the unique eigenvalues, measure the size of that array and use that size with the for loop instead.
eig_count = size(m,1) % Only returns the number of rows in m
for i = 1:eig_count
fprintf('eigenvalue %d has multiplicity %i\n',M(i),m(i))
end

Categories

Find more on Linear Algebra in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!