# Random matrix generation

Discussion in 'Mac Programming' started by dukebound85, Sep 27, 2011.

1. ### dukebound85 macrumors P6

Joined:
Jul 17, 2005
Location:
5045 feet above sea level
#1
Hi all, I have a quick question. I am trying to make a stochastic model within Matlab. Essentially I want to have a 100length array that with every time step, a random 50 of those indexes get something added to it.

Here is what I have
Code:
```close all
clear all

m_large = 10^-7; %grams
m_small = 10^-8; %grams

large_matrix = m_large*ones(100,1);
small_matrix = m_small*ones(100,1);

array = [1:1:100];

n_array = large_matrix;

for timestep = 1:10
x = randperm(50); %gives 50 radom indexes without repeating
index = x;
for i = 1:100
for j = 1:length(x)
n_array(x(j)) = large_matrix(x(j))+10^-8;
end
end

end
```
Right now, I am trying to get one timestep to work. The problem I am running into is that when I try to pull the index from x (say x(1) = 42, I then want the 42 index in n_array to be added to) seems not to work..ie it adds to the first 50 elements in n_array, so not random like I am trying to obtain.

Any ideas?

Thanks!

2. ### Hansr macrumors 6502a

Joined:
Apr 1, 2007
#2
I'm trying to understand the issue. So a 10x50 matrix with random variables from 1 to 100?

3. ### Hansr macrumors 6502a

Joined:
Apr 1, 2007
#3

Code:
```m_large = 10^-7; %grams
m_small = 10^-8; %grams

large_matrix = m_large*ones(100,1);
small_matrix = m_small*ones(100,1);

array = [1:1:100];

n_array = large_matrix;

elements_at_a_time = 50;

for timestep = 1:10
indices = floor(rand(elements_at_a_time,1)*max(array)+1);
n_array(indices) = n_array(indices)+m_small;
end```

4. ### SidBala macrumors 6502a

Joined:
Jun 27, 2010
#4
tl;dr: Use randperm(100,50)

I am not sure what you are trying to do exactly. But I think your understanding of randperm is incorrect.

randperm(50) will generate an array with 50 elements containing numbers 1 to 50.

If you use the values in the result of randperm(50) as indices to a larger matrix, the operation you are doing will affect the first 50 values of that large matrix.

Order of the operation will be random but you will always operate on the first 50 values only.

I think you want to use randperm(n,k)

where n is largest array index you want and k is 50. Try that out.

5. ### Sydde macrumors 68020

Joined:
Aug 17, 2009
#5
Then would it work to use randperm(100) and just use any 50 sequential values from that index array?

6. ### dukebound85 thread starter macrumors P6

Joined:
Jul 17, 2005
Location:
5045 feet above sea level
#6
For some reason, randperm does not work! However, What I did was as follows

y = randperm(100)
for i = 1:50
x(i) = y(i);
end

Thanks for the help though any idea why randperm wouldn't work? is it unique to the 2011b version? I tried the examples they had on matlab manual so no clue!

Anyways thanks