Home > front end >  generate a matrix with numbers between [0,1]
generate a matrix with numbers between [0,1]

Time:01-12

I have to generate a matrix of n x n uniformly distributed random numbers (n read from keyboard). The numbers should be between [0,1] and then to average the numbers > 0.5. I've tried the following:

value = 'Insert a value for n: ';
x = input(value);

matrix = rand(x,x);

matrix2(matrix < 0.5) = nan;

average = mean(matrix2, 'omitnan');
disp(average);

After I run the code I get that average is 0 and I don't know why.

CodePudding user response:

In your code, the line matrix2(matrix < 0.5) = nan; is the first time you mention matrix2, so this actually creates the matrix2. This "creation" indexing syntax ends up creating matrix2 with the same size as matrix, filling the elements where matrix < 0.5 with nan, and it will actually leave the other elements as 0.

What you want is to start out with matrix2 as a copy of matrix, and then set the elements, in other words

matrix2 = matrix;
matrix2(matrix2 < 0.5) = nan;
  •  Tags:  
  • Related