# dividing a diagonal matrix into same and different diagonal elements

14 views (last 30 days)
Sadiq Akbar on 16 May 2021
Commented: Dyuman Joshi on 17 May 2021
I have a diagonal matrix as:
V = [ 0.0001 0 0 0 0;
0 0.0001 0 0 0;
0 0 3.6388 0 0;
0 0 0 5.3610 0;
0 0 0 0 6.0004];
I want to find the number of diagonal elements which are same in values. 2ndly I want to separate them in a variable, how will I do it? Here V is a 5x5 matrix, but it may be any square size matrix in general.
##### 1 CommentShowHide None
Dyuman Joshi on 16 May 2021
Check my edited answer

Dyuman Joshi on 16 May 2021
Edited: Dyuman Joshi on 16 May 2021
%This will give the diagonal elements in a separate variable.
z = diag(V);
%Finding the number of repeated values
y = unique(z);
n = histc(z,y);
x = n(n>1); %If there are more than 1 repeating values, answer will be an array
a = y(n>1); %Get the variables that are repeated
Dyuman Joshi on 17 May 2021
Is it necessary to use functions? Your code is not the optimised way to write functions.