How do I randomly select a zero in a matrix and replace it with a value from another matrix?

조회 수: 1 (최근 30일)
I have a 52x3 zero matrix and a 1x15 matrix. A=[40 46 9 11 9 45 10 14 12 2 1 8 41 25 31];
I am trying to select the (1+n) value in A; (where n=0 for the first iteration and iterations<15) and randomly replace a zero in the zero matrix with this value.

채택된 답변

Image Analyst
Image Analyst 2015년 2월 10일
Try this:
out = zeros(52,3);
A=[40 46 9 11 9 45 10 14 12 2 1 8 41 25 31];
for k = 1 : length(A)
% Get a random location in out.
index = randi(numel(out), 1);
% Assign the kth element of A to it.
out(index) = A(k);
end
% Print to command window:
out
  댓글 수: 3
Image Analyst
Image Analyst 2015년 2월 10일
If you want it not exactly randomized, you can use randperm() like Star suggested. It makes sure that you don't use the same location twice, so you'll always have 15 numbers in there. If it were totally random, it's possible that you might have one location be the same as an earlier location if you're getting random locations in a for loop like you asked for. But you may not want that. You can have them all be different, which is maybe what you want, but it's not 100% random in that case. Anyway, here's the code:
% To do it vectorized (no for loop)
indexes = randperm(numel(out), length(A))
out(indexes) = A;
Image Analyst
Image Analyst 2015년 2월 10일
You're welcome. Thanks for accepting. By the way, the concept I used is called "linear indexing" and is a way of numbering the elements from first to last. In this way you don't have to get two random numbers - a row and a column. Linear and logical indexing are definitely something you will need to learn about as you proceed in your MATLAB programming.

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

추가 답변 (1개)

Youssef  Khmou
Youssef Khmou 2015년 2월 10일
The description is not complete, because localization of position in zero matrix requires two indexes x and y try :
B=zeros(52,3);
for n=0:15
xIndex=ceil(15*rand);
yIndex=ceil(3*rand);
B(xIndex,yIndex)=A(xIndex);
end
The question is why we chose the expression for yIndex and xIndex? and is the program complete ?

카테고리

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