Skip to Main Content Skip to Search
Login
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Thread Subject: How to retrive random values from a given matrix

Subject: How to retrive random values from a given matrix

From: Ruben

Date: 4 Jul, 2008 13:31:32

Message: 1 of 19

Hello Everyone,

I have a question on how to retrieve a random value from a matrix in Matlab. I have created a matrix and I will like to randomly take a value from that matrix, but I don't really now how to do that. I will appreciate any help.


Thanks in advance
 Ruben

Subject: How to retrive random values from a given matrix

From: John D'Errico

Date: 4 Jul, 2008 14:11:01

Message: 2 of 19

Ruben <colegio22@yahoo.com> wrote in message
<22884065.1215178323627.JavaMail.jakarta@nitrogen.mathforum.org>...
> Hello Everyone,
>
> I have a question on how to retrieve a random value from a matrix in
Matlab. I have created a matrix and I will like to randomly take a value from
that matrix, but I don't really now how to do that. I will appreciate any help.


Suppose I asked how to take the kth element
from your matrix. Would you know how to do
that?

So then all you need to know is how to generate
a random integer (k) from the set 1:n, where
n = numel(A), and A is your matrix.

What would you get if you took rand(1)*n?

This would be a floating point number of
course. Then what would ceil do? Try it.

Can you now generate what you need? You
should be able to do so.

John


Subject: How to retrive random values from a given matrix

From: Ruben

Date: 4 Jul, 2008 16:05:21

Message: 3 of 19

John,
  Thank you for you advice, I have tried what you suggested but it did not work. Let me try to explain better what I need.

If a have:
A=[3 10 7;5 8 1]

Now I will like to perform a command that will give me randomly any of the number within the previous matrix.

Thank you in advance
Ruben

Subject: How to retrive random values from a given matrix

From: John D'Errico

Date: 4 Jul, 2008 16:40:05

Message: 4 of 19

Ruben <colegio22@yahoo.com> wrote in message
<15820870.1215187552841.JavaMail.jakarta@nitrogen.mathforum.org>...
> John,
> Thank you for you advice, I have tried what you suggested but it did not
work. Let me try to explain better what I need.
>
> If a have:
> A=[3 10 7;5 8 1]
>
> Now I will like to perform a command that will give me randomly any of the
number within the previous matrix.
>
> Thank you in advance
> Ruben

No, I don't think that you did try what
I suggested, because it will work very
nicely. So why not show us what you
tried? Or make a second attempt. It will
indeed work if you seriously try it.

John

Subject: How to retrive random values from a given matrix

From: Jos

Date: 4 Jul, 2008 18:10:05

Message: 5 of 19

Ruben <colegio22@yahoo.com> wrote in message
<15820870.1215187552841.JavaMail.jakarta@nitrogen.mathforum.
org>...
> Thank you for you advice, I have tried what you
suggested but it did not work.

So, what did you try and why is it not working properly?
Show us some code, and you might learn from your mistakes!

> Let me try to explain better what I need.
>
> If a have:
> A=[3 10 7;5 8 1]
>
> Now I will like to perform a command that will give me
randomly any of the number within the previous matrix.

You already did a nice job formulating your problem.

Jos

Subject: How to retrive random values from a given matrix

From: Ruben

Date: 4 Jul, 2008 18:34:26

Message: 6 of 19

Well I will present to you here what I understood from what you tell me do try:
A=[3 12 1;4 6 9]
n=numel(A)
rand(1)*n

A =

     3 12 1
     4 6 9

n =

     6

ans =

       4.5464

Please let me know what I am doing wrong and if you can give me an example will be even better, Thank you once again for your help

Ruben

Subject: How to retrive random values from a given matrix

From: dpb

Date: 4 Jul, 2008 18:56:57

Message: 7 of 19

Ruben wrote:
> Well I will present to you here what I understood from what you tell me do try:
...
> Please let me know what I am doing wrong and if you can give me an
> example will be even better, Thank you once again for your help

Well, you would have to scale by upper and lower bounds and convert to
integer form...

irand = rand*(length(array) - 1) + 1

will scale the random value between 1 and length(array) but will, as you
discovered be non-integer. round(), fix(), ceil() would fix that.

OTTOMH, I'm not sure which would be the best choice for unbiased
rounding to the actual index to use.

Another way, particularly if the size isn't too large in practice is to
use the first value of

randperm(length(array))

which will be a random permutation of the values.

If you're selecting sequentially w/o replacement, walking thru the
vector will give one random chain; repeating the call would provide another.

If you want multiple values w/ replacement, then the vector needs to be
generated anew.

--

Subject: How to retrive random values from a given matrix

From: dpb

Date: 4 Jul, 2008 19:30:22

Message: 8 of 19

dpb wrote:
...
> Well, you would have to scale by upper and lower bounds and convert to
> integer form...
>
> irand = rand*(length(array) - 1) + 1
>
> will scale the random value between 1 and length(array) but will, as you
> discovered be non-integer. round(), fix(), ceil() would fix that.
>
> OTTOMH, I'm not sure which would be the best choice for unbiased
> rounding to the actual index to use.
...

Just dawned on me--if scale from 1 to length(array), the sampling for
the two end bins will be low by half compared to the middle ones.
Sampling needs to go from -0.5 to length() + 0.5 and round (fairly) to
midpoint of each integer interval.

Try this where

n <-- number/size of random index array values desired
l = length(array);

ridx = round(rand(n)*l - 0.5) + 1;

As demonstration, try the following

 >> ridx = round(rand(100000,1)*6 - 0.5) + 1;
 >> hist(ridx,6)

The plot should have almost equal-height bins of magnitude 100000/6 =
16666.6666...

The more samples, the better it will approach the expected value.

--

Subject: How to retrive random values from a given matrix

From: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)

Date: 4 Jul, 2008 19:55:35

Message: 9 of 19

In article <g4ltta$4e2$1@aioe.org>, dpb <none@non.net> wrote:

>Just dawned on me--if scale from 1 to length(array), the sampling for
>the two end bins will be low by half compared to the middle ones.
>Sampling needs to go from -0.5 to length() + 0.5 and round (fairly) to
>midpoint of each integer interval.

Don't use round, use floor() and add 1.

>n <-- number/size of random index array values desired
>l = length(array);

ridx = floor(rand(1,n)*l) + 1;
--
  "Do not wait for leaders. Do it alone, person to person."
                                              -- Mother Teresa

Subject: How to retrive random values from a given matrix

From: dpb

Date: 4 Jul, 2008 20:13:55

Message: 10 of 19

Walter Roberson wrote:
> In article <g4ltta$4e2$1@aioe.org>, dpb <none@non.net> wrote:
>
>> Just dawned on me--if scale from 1 to length(array), the sampling for
>> the two end bins will be low by half compared to the middle ones.
>> Sampling needs to go from -0.5 to length() + 0.5 and round (fairly) to
>> midpoint of each integer interval.
>
> Don't use round, use floor() and add 1.

Reason/logic behind that?

Agree it has similar properties and is simpler to write but in testing
here doesn't seem to make any significant difference in the bias on a
per bin basis. If round() is fair it would seem as equivalent in theory.

Did this several times and the following results are typical...always
seemed to get one bin about 1.5% low either way. Interestingly, in
about 20 trials (admittedly a _very_ small number) there wasn't a bin
high by that amount in either formulation.

 >> ridx = round(rand(10000,1)*6 - 0.5) + 1;
 >> bins = histc(ridx,[1:6])'
bins =
     16737 16760 16372 16591 16810 16730
 >> bins*6/100000
ans =
     1.0042 1.0056 0.9823 0.9955 1.0086 1.0038

 >> ridx = floor(rand(100000,1)*6) + 1;
 >> bins = histc(ridx,[1:6])'
bins =
     16811 16552 16596 16448 16779 16814
 >> bins*6/100000
ans =
     1.0087 0.9931 0.9958 0.9869 1.0067 1.0088

--

Subject: How to retrive random values from a given matrix

From: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)

Date: 4 Jul, 2008 20:58:59

Message: 11 of 19

In article <g4m0eu$e4q$1@aioe.org>, dpb <none@non.net> wrote:
>Walter Roberson wrote:

>> Don't use round, use floor() and add 1.

>Reason/logic behind that?

Easier to code and understand and more efficient.

If you use floor(N*rand)+1 then you have two sources of bias:

A) rand() cannot produce 0 or 1 -exactly-. This is fine for
the upper bin: if rand -did- produce 1 -exactly- then
floor(N*rand)+1 could produce N+1, which you don't want anyhow.
Effectively, then, the upper bin will have the same statistical
properties as all of the other bins -except- the lowest bin.
The lowest bin will be one count short of the number of distinct values
that can be in the bin. The shortage is 1 in 2^53, I think it is.

B) If N is relatively prime to the number of double precision
numbers between [0 1) then after scaling the rand value by 1,
some bins would "pigeon hole" a different number of possible
random values than others. For example, if N was 3 and we were to
look at quads of bits, [* x x *|x x * x|x * x x|* x x *|etc]
and we see that 1 out of 3 of those groups of 4 have two counts
but the other 2 of 3 have only 1. Some bins will therefore get
statistically overcounted.

The statistical overcount problem would occur for round() as well,
but it is {I suspect} more complex to analyze.

When you use round() note that (at least in 2007a) round
is "round away from zero"... unless you've set "round to
even" behaviour (as is mathematically recommended for systems
that matlab allows it to be set on.)
--
  "I feel sorry for the person who can't get genuinely excited
  about his work. Not only will he never be satisfied, but he will
  never achieve anything worthwhile." -- Walter Chrysler

Subject: How to retrive random values from a given matrix

From: Nitin Chhabra

Date: 7 Jul, 2008 07:05:04

Message: 12 of 19

roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote in
message <g4m2uj$ecc$1@canopus.cc.umanitoba.ca>...
> In article <g4m0eu$e4q$1@aioe.org>, dpb <none@non.net>
wrote:
> >Walter Roberson wrote:
>
> >> Don't use round, use floor() and add 1.
>
> >Reason/logic behind that?
>
> Easier to code and understand and more efficient.
>
> If you use floor(N*rand)+1 then you have two sources of
bias:
>
> A) rand() cannot produce 0 or 1 -exactly-. This is fine
for
> the upper bin: if rand -did- produce 1 -exactly- then
> floor(N*rand)+1 could produce N+1, which you don't want
anyhow.
> Effectively, then, the upper bin will have the same
statistical
> properties as all of the other bins -except- the lowest
bin.
> The lowest bin will be one count short of the number of
distinct values
> that can be in the bin. The shortage is 1 in 2^53, I
think it is.
>
> B) If N is relatively prime to the number of double
precision
> numbers between [0 1) then after scaling the rand value
by 1,
> some bins would "pigeon hole" a different number of
possible
> random values than others. For example, if N was 3 and we
were to
> look at quads of bits, [* x x *|x x * x|x * x x|* x x
*|etc]
> and we see that 1 out of 3 of those groups of 4 have two
counts
> but the other 2 of 3 have only 1. Some bins will
therefore get
> statistically overcounted.
>
> The statistical overcount problem would occur for round()
as well,
> but it is {I suspect} more complex to analyze.
>
> When you use round() note that (at least in 2007a) round
> is "round away from zero"... unless you've set "round to
> even" behaviour (as is mathematically recommended for
systems
> that matlab allows it to be set on.)
> --
> "I feel sorry for the person who can't get genuinely
excited
> about his work. Not only will he never be satisfied,
but he will
> never achieve anything worthwhile." -- Walter
Chrysler

Hi

Here is the simple way of the above question :
if a is given matrix of m*n dimension.

x=randperm(size(a,1)) % gives m random number vector
y=randperm(size(a,2)) % gives n random number vector
a(x(1),y(1)) % gives the random number from a matrix.

with regards,
Nitin

Subject: How to retrive random values from a given matrix

From: us

Date: 7 Jul, 2008 08:40:04

Message: 13 of 19

roberson@ibd.nrc-cnrc.gc.ca:
<SNIP on creating integer randoms...

> Don't use round, use floor() and add 1.
> >n <-- number/size of random index array values desired
> >l = length(array);
> ridx = floor(rand(1,n)*l) + 1;

one of the other (simpler) solutions

     rng=5;
     n=5;
     rn=ceil(rng*rand(1,n))
% eg, for one run
% rn = 5 5 1 5 4

us

Subject: How to retrive random values from a given matrix

From: us

Date: 7 Jul, 2008 08:45:04

Message: 14 of 19

"Nitin Chhabra"

> x=randperm(size(a,1)) % gives m random number vector
> y=randperm(size(a,2)) % gives n random number vector
> a(x(1),y(1)) % gives the random number from a matrix...

this solution is fine as long as the OP does not want
repeated data...

also, if he/she chooses this approach, a simpler solution
would be

     n=4; % <- # of randomly selected entries...
     m=magic(4);
     rn=randperm(numel(m)); % <- linear indexing...
     r=m(rn(1:n)) % <- linear indexing...

us

Subject: How to retrive random values from a given matrix

From: Nitin Chhabra

Date: 7 Jul, 2008 09:00:05

Message: 15 of 19

"us " <us@neurol.unizh.ch> wrote in message
<g4sl2f$eck$1@fred.mathworks.com>...
> "Nitin Chhabra"
>
> > x=randperm(size(a,1)) % gives m random number vector
> > y=randperm(size(a,2)) % gives n random number vector
> > a(x(1),y(1)) % gives the random number from a matrix...
>
> this solution is fine as long as the OP does not want
> repeated data...
>
> also, if he/she chooses this approach, a simpler solution
> would be
>
> n=4; % <- # of randomly selected entries...
> m=magic(4);
> rn=randperm(numel(m)); % <- linear indexing...
> r=m(rn(1:n)) % <- linear indexing...
>
> us

hi us,

I am not able to get your approach.
Could you please explain it a bit more.

One more thing as asked before , if a is given matrix of
any dimension ( say 3*4 ) , how this will select any one
element of the matrix.

I am getting vector as output if I run the code above.

You might use my personal email if you wana add some
picture /screen shots or result for clarification

with regards,
Nitin

Subject: How to retrive random values from a given matrix

From: us

Date: 7 Jul, 2008 09:30:09

Message: 16 of 19

"Nitin Chhabra"
<SNIP should read the % <- comments...

> I am not able to get your approach.
> how this will select any one element of the matrix.
> I am getting vector as output if I run the code above.

     n=4; % <- # of randomly selected entries...
     m=magic(4);
     rn=randperm(numel(m)); % <- linear indexing...
     r=m(rn(1:n)) % <- linear indexing...

% 1) any ONE (literally):
     n=1;
% 2) you get a vec - because - n=4

us

Subject: How to retrive random values from a given matrix

From: Nitin Chhabra

Date: 7 Jul, 2008 09:52:01

Message: 17 of 19

"us " <us@neurol.unizh.ch> wrote in message <g4snn1
$3is$1@fred.mathworks.com>...
> "Nitin Chhabra"
> <SNIP should read the % <- comments...
>
> > I am not able to get your approach.
> > how this will select any one element of the matrix.
> > I am getting vector as output if I run the code above.
>
> n=4; % <- # of randomly selected entries...
> m=magic(4);
> rn=randperm(numel(m)); % <- linear indexing...
> r=m(rn(1:n)) % <- linear indexing...
>
> % 1) any ONE (literally):
> n=1;
> % 2) you get a vec - because - n=4
>
> us

Hi us,

Sorry for not making myself clear in last message, I had
read the comments.Comments states what the function is
doing but i asked for approach ie algorithm/flow.

In other words :

If you read initial message from RUBEN, where he mentioned:

If I have: A=[3 10 7;5 8 1]
Now I will like to perform a command that will give me
randomly any of the number within the previous matrix.

Now coming to your code.....where is matrix A ....??
Which element of "A" is selected ??

I hope now it is clear what i want.

with regards,
Nitin

Subject: How to retrive random values from a given matrix

From: someone

Date: 7 Jul, 2008 20:10:03

Message: 18 of 19

"Nitin Chhabra" <nitin.chhabra@st.com> wrote in message
<g4sp01$c6j$1@fred.mathworks.com>...
> "us " <us@neurol.unizh.ch> wrote in message <g4snn1
> $3is$1@fred.mathworks.com>...
> > "Nitin Chhabra"
> > <SNIP should read the % <- comments...
> >
> > > I am not able to get your approach.
> > > how this will select any one element of the matrix.
> > > I am getting vector as output if I run the code above.
> >
> > n=4; % <- # of randomly selected entries...
> > m=magic(4);
> > rn=randperm(numel(m)); % <- linear indexing...
> > r=m(rn(1:n)) % <- linear indexing...
> >
> > % 1) any ONE (literally):
> > n=1;
> > % 2) you get a vec - because - n=4
> >
> > us
>
> Hi us,
>
> Sorry for not making myself clear in last message, I had
> read the comments.Comments states what the function is
> doing but i asked for approach ie algorithm/flow.
>
> In other words :
>
> If you read initial message from RUBEN, where he
mentioned:
>
> If I have: A=[3 10 7;5 8 1]
> Now I will like to perform a command that will give me
> randomly any of the number within the previous matrix.
>
> Now coming to your code.....where is matrix A ....??
> Which element of "A" is selected ??
>
> I hope now it is clear what i want.
>
> with regards,
> Nitin

In us's code, simply substitute A for m.

In other words, replace

m=magic(4);

with

A=[3 10 7;5 8 1];
m=A;

Now, if you only want one randomly selected value from A
(instead of 4), change n=4 to n=1 in us's code.

Subject: How to retrive random values from a given matrix

From: Nitin Chhabra

Date: 8 Jul, 2008 03:39:02

Message: 19 of 19

"someone " <someone@somewhere.net> wrote in message
<g4tt6r$500$1@fred.mathworks.com>...
> "Nitin Chhabra" <nitin.chhabra@st.com> wrote in message
> <g4sp01$c6j$1@fred.mathworks.com>...
> > "us " <us@neurol.unizh.ch> wrote in message <g4snn1
> > $3is$1@fred.mathworks.com>...
> > > "Nitin Chhabra"
> > > <SNIP should read the % <- comments...
> > >
> > > > I am not able to get your approach.
> > > > how this will select any one element of the matrix.
> > > > I am getting vector as output if I run the code
above.
> > >
> > > n=4; % <- # of randomly selected entries...
> > > m=magic(4);
> > > rn=randperm(numel(m)); % <- linear indexing...
> > > r=m(rn(1:n)) % <- linear indexing...
> > >
> > > % 1) any ONE (literally):
> > > n=1;
> > > % 2) you get a vec - because - n=4
> > >
> > > us
> >
> > Hi us,
> >
> > Sorry for not making myself clear in last message, I
had
> > read the comments.Comments states what the function is
> > doing but i asked for approach ie algorithm/flow.
> >
> > In other words :
> >
> > If you read initial message from RUBEN, where he
> mentioned:
> >
> > If I have: A=[3 10 7;5 8 1]
> > Now I will like to perform a command that will give me
> > randomly any of the number within the previous matrix.
> >
> > Now coming to your code.....where is matrix A ....??
> > Which element of "A" is selected ??
> >
> > I hope now it is clear what i want.
> >
> > with regards,
> > Nitin
>
> In us's code, simply substitute A for m.
>
> In other words, replace
>
> m=magic(4);
>
> with
>
> A=[3 10 7;5 8 1];
> m=A;
>
> Now, if you only want one randomly selected value from A
> (instead of 4), change n=4 to n=1 in us's code.
>

Thanks !!

Today I have learn one new thing !!
Obviously us's code is simple and compact !!

with regards,
Nitin

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
ceil us 7 Jul, 2008 04:45:07
rand us 7 Jul, 2008 04:45:07
randperm us 7 Jul, 2008 04:45:07
linear indexing us 7 Jul, 2008 04:45:07
code us 7 Jul, 2008 04:45:07
rssFeed for this Thread

envelope graphic E-mail this page to a colleague

Public Submission Policy
NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Disclaimer prior to use.
Related Topics