Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

dukebound85

macrumors Core
Original poster
Jul 17, 2005
19,218
4,342
5045 feet above sea level
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!
 
I'm trying to understand the issue. So a 10x50 matrix with random variables from 1 to 100?
 
Still not sure if I understand but how about this?

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
 
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.
 
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.