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!