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

采纳的回答

Jorrit Montijn
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
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
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.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by