1

I was expecting that the following code would populate E with random 1's and 0's, but that does not happen. I cannot figure out why.

Pkg.add("StatsBase")
using StatsBase

function randomSample(items,weights)
    sample(items, Weights(weights))
end



n = 10
periods = 100

p = [ones(n,periods)*0.5]
E = fill(NaN, (n,periods))

for i in 1:periods
    for ii in 1:n
        E(ii,i) = randomSample([1 0],[(p(ii,i)), 1 - p(ii,i)])
    end
end
E
2
  • 2
    Unlike MATLAB, indexing is done with brackets in Julia not with parentheses. Be careful with the brackets, though, [ones(5, 10)] will give you an Array of Array(s). In MATLAB, however, it makes no difference to add as many surrounding brackets as possible: the result will be just a matrix. Commented May 6, 2019 at 22:03
  • 2
    Since you are already using fill to initialize E, why not do the same with p:? That is, p = fill(0.5, (n, periods)). This is more efficient (and reasonable) than first creating a matrix of ones, and then creating a second matrix by multiplying the first one with 0.5. Commented May 7, 2019 at 6:37

1 Answer 1

2

The statement:

E(ii,i) = randomSample([1 0],[(p(ii,i)), 1 - p(ii,i)])

defines a local function E and is not an assignment operation to a matrix E. Use

E[ii,i] = randomSample([1, 0],[p[ii,i], 1 - p[ii,i]])

(I have fixed additional errors in your code so please check out the differences)

and for it to run you should also write:

p = ones(n,periods)*0.5
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.