how do I substitute all negative values in a vector with a random number between 0 and 2

4 ビュー (過去 30 日間)
Malavan Subramaniam
Malavan Subramaniam 2019 年 9 月 17 日
回答済み: Shounak Shastri 2019 年 9 月 17 日
How do I substitute all negative values in a vector (called y) with a random number between 0 and 2?

回答 (3 件)

per isakson
per isakson 2019 年 9 月 17 日
One way
>> Y = randi( [-4,4], 1,12 ); % sample vector
>> isneg = Y < 0;
>> Y( isneg ) = 2*rand( 1, sum(isneg) )
Y = Columns 1 through 10
2 0.69135 0 2 0 0.72759 1.7308 2 0 3
Columns 11 through 12
1 0

Stephan
Stephan 2019 年 9 月 17 日
y(y<0) = 2*rand(1,numel(y(y<0)))

Shounak Shastri
Shounak Shastri 2019 年 9 月 17 日
The simplest (but not the most efficient) way to do this would be to inititalize a for loop and run through all the elements one-by-one.
for ii = 1:length(y)
if y(ii) < 0
y(ii) = randi([0, 2]);
end
end
The function randi() generates a random number bertween the limits given in the square brackets, in this case 0 and 2.
A better (faster and more efficient in terms of lines of code) way to do this would be
y (y < 0) = randi([0, 2]);

カテゴリ

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