Filling Rand matrix with specific numbers
Show older comments
Good evening,
Lets say i have a=rand(1500,1000) and I need to fill 1:300 numbers with ones, 300:600 with 0.75, 900:1200 with 0.5 and so on.. And then show as a picture. I feeling stuck on this one:/
7 Comments
the cyclist
on 25 Mar 2020
Sounds like homework. What have you tried?
Also, why are you starting with matrix filled with random values, and then overwriting them with non-random values? (Or maybe I misunderstand what mean.)
darova
on 25 Mar 2020
- I need to fill 1:300 numbers with ones
You have 2D matrix. Where are those numbers?
Image Analyst
on 25 Mar 2020
a(1, 1:300) = 1; % Set first 300 columns in row 1 to be 1.
Also look at the handy functions repelem() and repmat().
Deividas Silgalis
on 25 Mar 2020
the cyclist
on 26 Mar 2020
Note that these lines
matrix0(1200:1500, 1:1000) = 0;
matrix0(1200:1500, 1:1000) = 0;
should be
matrix0(1201:1500, 1:1000) = 0;
matrix0(1201:1500, 1:1000) = 0;
Image Analyst
on 26 Mar 2020
Edited: Image Analyst
on 26 Mar 2020
or, in one line of code and using the "end" keyword:
matrix0(1201:end, :) = 0;
I don't know that your code is clumsy. Sometimes if there are just a small handful of things to do it's often more readable and maintainable just to spell it out like you did. Anyone can instantly see what's going on there, which may not be the case for a more cryptic specialized function call, and it might be just as many lines, if not fewer than constructing some loop to do the same thing.
the cyclist
on 26 Mar 2020
lol ... I somehow missed that those two lines of code were identical. :-)
Accepted Answer
More Answers (2)
Image Analyst
on 26 Mar 2020
I don't know that your code is clumsy. Sometimes if there are just a small handful of things to do it's often more readable and maintainable just to spell it out like you did. Anyone can instantly see what's going on there, which may not be the case for a more cryptic specialized function call, and it might be just as many lines, if not fewer than constructing some loop to do the same thing.
If you'd really like to do it with MATLAB functions, and not explicity/directly like you did, then you can do this:
% Define the values we want to put into the matrix.
verticalProfile = [1; 0.75; 0.5; 0.25; 0]
% Replicate these vertically the full height of 1500 rows
% by duplicating each number 300 times.
column1 = repelem(verticalProfile, 300);
% Copy this line all the way across 1000 columns.
matrix0 = repmat(column1, [1, 1000]);
Not including comments, that's 3 lines of code instead of your 7 lines of code. But it's not as readable as yours since now someone has to know that repelem() and repmat() do. I think it definitely looks more cryptic.
Deividas Silgalis
on 28 Mar 2020
0 votes
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!