Replace all instances of a value with random number

3 ビュー (過去 30 日間)
ME
ME 2020 年 1 月 2 日
コメント済み: ME 2020 年 1 月 2 日
I am currently trying to replace all instances of the value 1 in an array with a different random number.
For example, if I have
A = [1 0 1 0;
0 1 0 0;
1 0 0 0;
1 1 0 1];
then I want a simple piece of code to quickly get something like:
A = 0.7144 0 0.1217 0;
0 0.9840 0 0;
0.5931 0 0 0;
0.2695 0.4320 0 0.9305];
I have tried using A(A==1)=rand but that filled in all of the 1s with th same random number.
I know this would be really easy to do using for loops but I am keen to avoid this because the A array will get quite large and end up being a drag on the performance of the overall script.

採用された回答

Jeremy
Jeremy 2020 年 1 月 2 日
A = [0 1 0 1; 1 0 1 1; 0 0 1 1];
id = A==1;
r = rand(1,nnz(id));
A(id) = r;
  1 件のコメント
ME
ME 2020 年 1 月 2 日
Awesome, thank you!

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

その他の回答 (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