Reduce the number of zeros in an array

3 Ansichten (letzte 30 Tage)
pavlos
pavlos am 29 Nov. 2016
Beantwortet: Jan am 29 Nov. 2016
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

Akzeptierte Antwort

Jorrit Montijn
Jorrit Montijn am 29 Nov. 2016
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 Kommentar
Jorrit Montijn
Jorrit Montijn am 29 Nov. 2016
I just realized you wanted to throw away 2/3 of the zeros. In this case, use:
vecRemoveZeros = randperm(intNumZeros,round(intNumZeros*(2/3)));

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jan
Jan am 29 Nov. 2016
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.

Community Treasure Hunt

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

Start Hunting!

Translated by