Find a random position in a vector where the value is zero

5 ビュー (過去 30 日間)
Murali Krishna AG
Murali Krishna AG 2021 年 7 月 25 日
編集済み: Scott MacKenzie 2021 年 7 月 25 日
I have a vector with mix of complex numbers and zeros. I have to find a random position in the vector where the value is zero.
For example, in the given A matrix I should get any of the underlined value's vector position
A = [a b c 0 x 0 0 0 r 0 0 0 y q 0 p 0];

採用された回答

Scott MacKenzie
Scott MacKenzie 2021 年 7 月 25 日
編集済み: Scott MacKenzie 2021 年 7 月 25 日
% test data (includes zeros and imaginary numbers)
A = [1i 4/1j 7 0 99 0 0 0 8*1j 0 0 0 8 9 0 -7 0];
% find indices of zeros in A
zeroIdx = find(A==0);
% pick one of the zeros at random (display index)
randomIdx = zeroIdx(randi(length(zeroIdx),1))
randonIdx = 6

その他の回答 (1 件)

Chunru
Chunru 2021 年 7 月 25 日
% Generate some randome data with zeros
n = 10;
a = randn(1, n);
k = randperm(n, round(n/2));
a(k) = 0;
a
a = 1×10
0 0 -1.5217 0 -1.5143 -0.0588 0 -0.0439 0 -1.0513
% find zeros
idx = find(a==0);
% randomly pick from idx
pick = randperm(length(idx), 1)
pick = 4
a(idx(pick))
ans = 0

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by