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

9 views (last 30 days)
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.

Accepted Answer

Image Analyst
Image Analyst on 10 Feb 2015
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);
% Print to command window:
Image Analyst
Image Analyst on 10 Feb 2015
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.

Sign in to comment.

More Answers (1)

Youssef  Khmou
Youssef Khmou on 10 Feb 2015
The description is not complete, because localization of position in zero matrix requires two indexes x and y try :
for n=0:15
The question is why we chose the expression for yIndex and xIndex? and is the program complete ?


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!

Translated by