mardi 25 juillet 2017

Set variables of certain value in a matrix or array to random values in matlab

I have matrix (or an array here for easier understanding), that is filled with values, e.g.:

[0 0 1 0 0 0 1 0 0 0 ]

Now I want to fill every element that is, for example 0 to a random value, but each one should be different.

If I do it like this:

replace_val = 0
x = [ 0 0 1 0 0 0 1 0 0 0 ]
x(x == replace_val) = rand

Then all 0 will be replaced with the same number, e.g.:

[ 0.8361    0.8361    1.0000    0.8361    0.8361    0.8361    1.0000    0.8361    0.8361    0.8361 ]

Now the most straight forward way is to create a loop that will iterate over the vector and at any time the condition is met, it will call the rand function like here:

for i=1:length(x)
  if x(i) == replace_val
   x(i) = rand;
  end
end

However, with matrices or very large arrays this will be very slow. So, I am wondering if there is any kind of fast, matlabish way to get the desired output?




Aucun commentaire:

Enregistrer un commentaire