How to use If and for Random Matrices???
Show older comments
generate a 5*8 matrix of random numbers and next write a programme using "for" and "if" loops to replace numbers less than 0.5 with "0" and numbers 0.5 or above with 1.
Answers (1)
H ZETT M
on 1 Aug 2017
So the way without the for and if loops is:
X=rand(5,8)
X(X<(0.5))=0;
X(X>(0.5))=1;
if you really want to use loops:
X=rand(5,8)
for i=1:5
for m=1:8
if X(i,m)<=0.5
X(i,m)=0;
else X(i,m)=1;
end
end
end
4 Comments
You've made a slight error in the comparisons, but as this is most likely homework, I would leave it as is and let the OP figure it out (and best would have been not to provide the loop method, they won't learn anything if you do their homework).
An even simpler way without a loop:
result = rand(5, 8) >= 0.5;
KSSV
on 1 Aug 2017
@H ZETT M ...it is not fair to answer home work questions...
Ahamed KMR
on 1 Aug 2017
Jan
on 1 Aug 2017
@Ahamed KMR: You are waiting H ZETT M's prompt action?! This sounds rather impolite considering the fact, that he or she has almost solved your homework. The remaining work to do is really tiny, so please do show any own effort.
Posting homework solutions is a drawback for the reputation of the forum. In my university posting solutions programmed by others without mentioning this clearly was treated as cheating and one can loose the status as student.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!