Reduce the number of zeros in an array
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello,
Please help me with the following:
I study some data that contain arrays with many repeated zeros.
I need to reduce the number of zeros by a certain number.
For example,
Consider the array
A=[1.140,0.590,0.140,0,0,0,0,0,0,0,0,0,0,0,0,1,3,5];
How can I reduce the number of zeros 3 times?
The number of zeros in A is 12 and I want to keep only 4.
The final array would be
B=[1.140,0.590,0.140,0,0,0,0,1,3,5];
Thank you.
Pavlos
댓글 수: 0
채택된 답변
Jorrit Montijn
2016년 11월 29일
Hi Pavlos,
I'm not sure what the purpose would be of reducing the number of zeros, but here's one way to do it by removing one randomly selected third of all zeros:
% First, define the vector:
A=[1.140,0.590,0.140,0,0,0,0,0,0,0,0,0,0,0,0,1,3,5];
% then search for the locations where the vector has zeros:
vecZeroLocations=find(A==0);
% count how many zeros there are:
intNumZeros=numel(vecZeroLocations);
% select one third of zeros to remove:
vecRemoveZeros = randperm(intNumZeros,round(intNumZeros/3));
% now we have to get the locations in the original vector of those zeros:
vecRemoveLocations = vecZeroLocations(vecRemoveZeros);
% and finally, we can remove those zeros from the vector:
A(vecRemoveLocations)=[];
I hope this answers your questions?
Best, Jorrit
댓글 수: 1
Jorrit Montijn
2016년 11월 29일
I just realized you wanted to throw away 2/3 of the zeros. In this case, use:
vecRemoveZeros = randperm(intNumZeros,round(intNumZeros*(2/3)));
추가 답변 (1개)
Jan
2016년 11월 29일
A = [1.140,0.590,0.140,0,0,0,0,0,0,0,0,0,0,0,0,1,3,5];
[B, N] = RunLength(A);
N(B == 0 & N > 4) = 4;
leanA = RunLength(B, N);
Now all runs of zeros have a maximum length of 4.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!