Filling Rand matrix with specific numbers

조회 수: 5 (최근 30일)
Deividas Silgalis
Deividas Silgalis 2020년 3월 25일
답변: Deividas Silgalis 2020년 3월 28일
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
Image Analyst
Image Analyst 2020년 3월 26일
편집: Image Analyst 2020년 3월 26일
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
the cyclist 2020년 3월 26일
lol ... I somehow missed that those two lines of code were identical. :-)

댓글을 달려면 로그인하십시오.

채택된 답변

darova
darova 2020년 3월 25일
Use for loops
matrix0=rand(1500,1000);
val = [1:-0.25:0];
for i = 1:5
ii = (i-1)*300+1 : i*300;
matrix0(ii,:) = val(i);
end
image(matrix0, 'CDataMapping', 'scaled');
or more elegant
val = repmat(1:-0.25:0,[300 1]); % copy 300 rows
% val(:) - make one column of 1500 elements (300x5)
val = repmat(val(:),[1 1000]);
image(val)

추가 답변 (2개)

Image Analyst
Image Analyst 2020년 3월 26일
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
Deividas Silgalis 2020년 3월 28일
Thanks you all for your answers. It helped me alot!

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by