Find amount of nonzero elements in matrix
Show older comments
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!
Accepted Answer
More Answers (2)
Read about nnz. This gives you number of non-zeros in the data.
4 Comments
Debbie Oomen
on 29 May 2018
KSSV
on 29 May 2018
You may follow like this:
A = [0,0,0,0,3,2,5,2,4,1,5,0,1,2,5,0,0,0,0,0,0,0,0,0,1,1,2,6,3,1];
t = 1:length(A) ;
ii = zeros(size(A));
jj = A > 0;
ii(strfind([0,jj(:)'],[0 1])) = 1;
idx = cumsum(ii).*jj;
x = accumarray( idx(jj)',t(jj)',[],@(x){x'});
y = accumarray( idx(jj)',A(jj)',[],@(x){x'});
for i = 1:length(x)
[x{i}' y{i}']
end
Debbie Oomen
on 29 May 2018
KSSV
on 29 May 2018
How did you try the code? I should see the code, you tried..along with data.
[Value, Repetitions, Index] = RunLength(CheckDataD1log)
2 Comments
Debbie Oomen
on 29 May 2018
Stephen23
on 29 May 2018
@Debbie Oomen: you need to download it from the link that Jan Simon gave you.
Categories
Find more on Matrices and Arrays 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!