MATLAB: Reduce the number of zeros in an array

arrayMATLABmatrix manipulationStatistics and Machine Learning Toolbox

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

Best Answer

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