How do I write a script that creates an M x N array of random numbers?

So I need to write a script that creates an M X N array of random numbers. Move through the array, element-by-element, and set any value that is less than 0.2 to 0, and any value that is greater than (or equal to) 0.2 to 1.

3 Comments

"I figured it out! Here is the answer if anyone needs it:"
Nope, that does not work. Here some reasons why:
  1. Syntax error because =< is not a MATLAB operator, and needs to be replaced with <=.
  2. The if operator "An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false." This means that your logical matrices must contain only true to execute the following statements. This will be a rare occurrence for that random matrix.
  3. The syntax else a > 0.2 is not an error, but serves no functional purpose as it simply displays the logical array a > 0.2. The correct operator would be elseif.
  4. The allocations a = 0 and a = 1 do not replace the zero elements, but simply reallocate the entire variable. This is not what the question requested.
  5. There is no looping or indexing to select which elements are being replaced.
For multiple reasons, this "solution" will fail.
A real solution would require a loop and using indexing. These are basic MATLAB programming features that are introduced in the introductory tutorials:
Although not fulfilling the question's requirement to work "element-by-element", simple logical indexing would be to best solution, as Andrei Bobrov's answer shows.
Original question by original author:
"How do I write a script that creates an M x N array of random numbers?"
So I need to write a script that creates an M X N array of random numbers. Move through the array, element-by-element, and set any value that is less than 0.2 to 0, and any value that is greater than (or equal to) 0.2 to 1.
Original comment by original author:
I figured it out!
Here is the answer if anyone needs it:
a = rand (4,5)
if a =< 0.2
a = 0
else a > 0.2
a = 1
end

Sign in to comment.

 Accepted Answer

just
a = rand(M,N) > .2;

1 Comment

Depends on if "element-by-element" wanted a "for loop" solution or a vectorized solution.
If it's a homework solution I'd hope the professor would accept either way since the problem statement was so ambiguous.

Sign in to comment.

More Answers (1)

M = 5;
N = 4;
a = rand(M,N);
a(a<=0.2) = 0;
a(a>0.2) = 1;

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

No tags entered yet.

Asked:

on 14 Dec 2016

Edited:

on 2 Sep 2025

Community Treasure Hunt

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

Start Hunting!