tags:

views:

318

answers:

3

I use this code to create and plot N points:

N = input('No. of Nodes:');
data = rand(N,2); % Randomly generated n no. of nodes
x = data(:,1);
y = data(:,2);

plot(x,y,'*')
hold on

How would I randomly pick one of these points?

+1  A: 
randnum=ceil(rand(1)*N)  %Sample a random integer in the range 0 to N
your_node = [x(randnum),y(randnum)] %Here is the sampled node from your data set

Edit: changed floor to ceil.
Ksiresh
hey thankx a lot my friend, you are great...
gurwinder
This solution isn't correct. It can generate the value `0` (which can't be used as an index) and will rarely (if ever) produce the value `N`.
gnovice
I stand corrected.
Ksiresh
+8  A: 

You can use the function RANDI to generate a random integer in a given range:

index = randi(N);             %# Generate a random integer in the range 1 to N
plot(x(index),y(index),'o');  %# Plot the point

EDIT: As pointed out by Mikhail, the RANDI function has only been available since version 7.7 (R2008b). For earlier versions, the following alternative should work:

index = ceil(rand*N);
gnovice
Good solution, but available, if I remember correctly, only for the last couple of Matlab versions. Generally speaking, MathWorks should put it in the help, beginning from which version a feature is available.
Mikhail
@Mikhail: You're right, it would be nice if they put that in the online help for each function. As it stands now, you have to check these release pages to figure it out: http://www.mathworks.com/access/helpdesk/help/techdoc/rn/rn_intro.html
gnovice
A: 

Just take the first one. Being a product of the rand()-function, it should be random enough for anybody :-)

plot(x(1),y(1),'o');

edgar.holleis
This would be fine for randomly generated points, but I think that was just an example the OP used to illustrate the problem.
gnovice
Then again, since the question is clearly entry level, the original poster might be headed for a real atrocity: The improving-random-by-random-antipattern. Makes me remember:int get_random_number() { return 4; /* Chosen truly randomly by dice-roll. */ }
edgar.holleis

related questions