Mixed Type Variables in Julia

Dear All,

How can we fix the issues from mixed type variable in Julia? now I convert these loops from Matlab to Julia; However, It seems not working in Julia …

Matlab

p = 1.0;
pr = 3.0;
tp = 2.0;
for i = 1:fix(pr/2)
inv = 1/nchoosek(pr,i);
mpi = min(p,i);
for j = max(0,i-tp):mpi
bezalfs(i+1,j+1) = inv*nchoosek(p,j)*nchoosek(tp,i-j);
bezalfs(pr-i+1,p-j+1) = bezalfs(i+1,j+1);
end
end

Julia:

p = 1.0
pr = 3.0
tp = 2.0
bezalfs = Array{Float64}(undef, 4, 2)

for i = 1:round(pr/2)
inv = 1/binomial(pr,i)
mpi = min(p,i)
for j = max(0,i-tp):mpi
bezalfs[i+1,j+1] = inv*binomial(p,j)*binomial(tp,i-j);
bezalfs[pr-i+1,p-j+1] = bezalfs[i+1,j+1];
end
end

Solution(Matlab)

bezalfs =

     0         0
0.6667    0.3333
0.3333    0.6667

Question: how can we solve this bug in a brilliant way in Julia?

It would help if you could include the error message, or what’s wrong with the output. However you may be looking for ÷, as in https://docs.julialang.org/en/v1/base/math/#Base.div

1 Like

@improbable22 is right. Use div(pr, 2) or pr ÷ 2 or pr >> 1 instead of round(pr/2), to get an integer.

Also, your preallocated matrix is 4-by-2 instead of 3-by-2 (you should probably calculate that size instead of hardcoding it, though).

Furthermore, please wrap your code in triple backticks (```), to make it easier to read, like this:

p = 1
pr = 3
tp = 2
bezalfs = Array{Float64}(undef, 3, 2)  # <- 3 not 4
for i in 1:div(pr, 2)  # div not /
    inv = 1/binomial(pr,i)
    mpi = min(p,i)
    for j in max(0,i-tp):mpi
        bezalfs[i+1,j+1] = inv*binomial(p,j)*binomial(tp,i-j);
        bezalfs[pr-i+1,p-j+1] = bezalfs[i+1,j+1];
    end
end

BTW, I see that I pointed you to this thread (PSA: make it easier to help you) less than a week ago, and specifically mentioned the use of triple backticks.

It would perhaps be a good idea to re-read that post.

1 Like

Thanks for your answer!

p = 1.0
pr = 3.0
tp = 2.0
bezalfs = Array{Float64}(undef, 3, 2)  # <- 3 not 4
for i in 1:div(pr, 2)  # div not /
    inv = 1/binomial(pr,i)
    mpi = min(p,i)
    for j in max(0,i-tp):mpi
        bezalfs[i+1,j+1] = inv*binomial(p,j)*binomial(tp,i-j);
        bezalfs[pr-i+1,p-j+1] = bezalfs[i+1,j+1];
    end
end

if input variable is double type, how can we deal with it brilliantly in Julia?

What’s the input variable? Does “double” mean Float64?

yes,

In Matlab, we can use

 p = 1.0
pr = 3.0
tp = 2.0

But in Julia,


p = 1.0
pr = 3.0
tp = 2.0

will never work, untill we switch these to integer variable …

Assuming I understand the question correctly, you can use floor(Int, pr/i) or Int(div(pr, i)). That should work both for integers and floats.

1 Like

yes, you are fully correkt! but why do we need JuliaStats/Distributions.jl package to solve this problem? such solution seems too too complex.

You don’t need it. Why do you think that you do?

1 Like