Find amount of nonzero elements in matrix
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Debbie Oomen
am 29 Mai 2018
Kommentiert: Guillermo
am 25 Nov. 2024
Hello all,
I have a matrix that contains two column. Column A is the time and column B is the value belonging to that time. Now, column B contains zero and nonzero elements. What I need to do is count all the zeros and nonzeros. So I choose for a logical that returns true if it is nonzero and false if it is zero. I need to count the amount of consecutive nonzero elements because this corresponds to the duration. I used the following code to do this:
CntsCheckDataD1 = CheckDataD1(:,2);
CheckDataD1log = CntsCheckDataD1 ~= 0;
CheckDataD1log = CheckDataD1log';
if (CheckDataD1log(1,1) == 0) == 1
CheckDataD1log = diff([0 find(diff(CheckDataD1log)) numel(CheckDataD1log)]);
CheckDataD1log = CheckDataD1log';
onesCheckDataD1log = CheckDataD1log(2:2:end, :);
else
CheckDataD1log = diff([0 find(diff(CheckDataD1log)) numel(CheckDataD1log)]);
CheckDataD1log = CheckDataD1log';
onesCheckDataD1log = CheckDataD1log(1:2:end, :)
end
This returns all amount of ones in the matrix. I need to check where the first amount of consecutive ones is more than (for example) 15 and return the corresponding time from the CheckDataD1 matrix. Finding this value in the onesCheckDataD1log is easy but I do not know how I can find the corresponding time belonging to that value in the CheckDataD1 matrix..
Please help!
0 Kommentare
Akzeptierte Antwort
Ameer Hamza
am 29 Mai 2018
Try regionprops(). It will tell you exactly how many times there are consecutive zeros groups, along with length and location of each group.
x = [ 1 0 0 0 1 2 0 0 0 1 1 0 0];
groups = regionprops(x==0)
groups =
3×1 struct array with fields: % <--- Indicating there are 3 groups of consecutive zeros
Area
Centroid
BoundingBox
To get the length of each group
[groups.Area]
ans =
3 3 2 % <---- Length of each group of zero, first group have 3 zeros, second has 3 and last have 2, same as in vector x
To get the location of each group
ceil(vertcat(groups.BoundingBox))
ans =
2 1 3 1
7 1 3 1
12 1 2 1
ignore the 2nd and 4 column. The first column indicates the starting position and the third column indicate the length. E.g. first row [2 1 3 1] indicate that first group start at location 2 and have three zeros.
1 Kommentar
Weitere Antworten (2)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!