how to generate random points in a matrix

hi , I have a problem here and need some help; suppose here we have a m*n matrix and we want to generate some points in a matrix(or in an image) randomly. how can I generate these points ? thanks in advance ; any comments will be appreciated .

1 Comment

What does this exactly mean: Generate some points in a m*n matrix? Do you want some random indices in the range 1:m and 1:n? Or do the values of the matrix matter?

Sign in to comment.

Answers (3)

If you have the Statistics Toolbox, you can use randsample() I'll assume a 256x256 matrix for this example.
indices = randsample(256^2,50);
[I,J] = ind2sub([256 256],indices);
The above gives you the row and column indices. However you can just use the output of randsample(), the linear indices to fill and extract values from the matrix.
X = randn(256,256);
X(indices) = 0;

2 Comments

thanks so much , its what i need . just a question , am i have to put the name of my image(matrix) instead of 'X' ?
yes, I don't have your data, so I just created an example with X as the data matrix
X = randn(256,256);

Sign in to comment.

Amin:
Run this code and see if it's what you are looking for.
% Generate a totally black image to start with.
m = zeros(300, 400, 'uint8');
% Generate 1000 random locations.
numRandom = 1000;
linearIndices = randi(numel(m), 1, numRandom);
% Set those lcoations to be white.
m(linearIndices) = 255;
% Display it. Random locations will appear white.
image(m);
colormap(gray);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
caption = sprintf('%d Random Pixels are Set to White', numRandom);
title(caption, 'FontSize', 30);

2 Comments

dear friend , thanks for the answer , but i can't check it , when ever i run this code , i see the error of the line which contain "randi" . i use matlab r2008a . the error is: " ??? Undefined function or method 'randi' for input arguments of type 'double'." i don't know what to do !!
Change the randi line to this and it will work:
linearIndices = ceil(numel(m) * rand(1, numRandom));

Sign in to comment.

thanks so much ,actually I'm a beginner and meantime i wrote this:
cl=input('cl no= ');
col1=zeros(cl,1);
col2=zeros(cl,1);
clcoordinate=zeros(21025,190);
for i=1:cl
col1(i)=fix(21025*rand);
col2(i)=fix(190*rand);
clcoordinate(col1(i),col2(i))=1;
end
here i can choose number of points and actually it works, but every time that I run the program, I'm getting the same result. Is there a way that I can generate some different number each time that program runs ?

1 Comment

fix(21025*rand) will result in 0, 1 in 42050 times.
fix(190*rand) will result in 0, 1 in 380 times.
There was a good reason why Image Analyst used ceil() instead of fix()

Sign in to comment.

Categories

Tags

Asked:

on 6 Nov 2011

Community Treasure Hunt

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

Start Hunting!