How to replace zeros in a vector with random segments of the same vector?

5 ビュー (過去 30 日間)
Bence Laczó
Bence Laczó 2022 年 3 月 24 日
編集済み: Bence Laczó 2022 年 3 月 25 日
I have a vector with 240000 data points. There are several, 72 elements long segments of zero values in that vector. Now I would like to replace these segments of zeros with random 72 elements long segments from the remaining non zero part of the vector.
Can you help me how can I do it?

採用された回答

Image Analyst
Image Analyst 2022 年 3 月 24 日
Try this:
% First we need to create the data since the original poster forgot to attach it for us.
% Make random vector with values in the 1-9 range.
v = randi(9, 1, 24000);
% Make 20 stretches of 72 zeros.
startingIndexes = sort(randi(length(v), 1, 20))
for k = 1 : length(startingIndexes)
v(startingIndexes(k) : startingIndexes(k) + 71) = 0;
end
% Now we have our vector and we can begin.
%---------------------------------------------------------------------------------
% First find out what the non-zero values are
% that we can use to plug the regions of zeros.
% tic; % Start timer
availableToUse = unique(nonzeros(v));
% Now plug the zeros with numbers randomly chosen from availableToUse
for k = 1 : length(v)
if v(k) == 0
% It's zero so replace it with a random number chosen from availableToUse.
randomIndex = randi(length(availableToUse), 1, 1);
v(k) = availableToUse(randomIndex);
end
end
% toc % End timer
Time to execute is 0.002 seconds (2 milliseconds).
  1 件のコメント
Bence Laczó
Bence Laczó 2022 年 3 月 25 日
編集済み: Bence Laczó 2022 年 3 月 25 日
Thank you very much for the help! I'm really appreciate your kindness!
I think I was not precise when I described my problem. I have to replace the 72 elements long segments of zeros, with random, but existing 72 elements long segments of the remaining data. So not with random single numbers, but with 72 consecutive numbers.
Now I have attached the original data.

サインインしてコメントする。

その他の回答 (1 件)

Arif Hoq
Arif Hoq 2022 年 3 月 24 日
try this:
A=[1 2 3 0 0 0 4 5 0 0 0 0 0 0 0 0 8 9]'; % any matrix
B=A(A==0); % extract the number of 0
rdnumber=randi([10 20],size(A,2),numel(B)); % generating random number
A(A==0)=rdnumber % replace with random number
A = 18×1
1 2 3 14 14 18 4 5 19 17
  1 件のコメント
Image Analyst
Image Analyst 2022 年 3 月 24 日
That is not using only the non-zero values to plug the zeros, like I do in my answer. You're including numbers not in the original vector.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGet Started with Statistics and Machine Learning Toolbox についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by