Function does not run correctly (Linear and Cartesian Indices)

Basically, I have a test function which I call from a main script in Atom.
However, the function returns NaN array as mA. Whereas, if I copy paste and run parts of the code inside REPL it runs without any issue. Where is the problem?
I even tried running test() function as a script (not a function) and I have the same problem.

function test()

    matrixSize=30;
    mX   = randn(matrixSize, matrixSize);

    # Assuming Samples are slong Columns (Rows are features)
    numClusters     = Int64( max( round(matrixSize / 100), 1 ) ); # % max between 1 and round(...)
    numIterations   = 10;

    # http://stackoverflow.com/questions/36047516/julia-generating-unique-random-integer-array
    mA = mX[:, randperm(matrixSize)[1:numClusters]] ; #<! Cluster Centroids

    for ii = 1:numIterations

        vMinDist, mClusterId = findmin( transpose(sum(mA .^ 2, dims=1)) .- (2 .* transpose(mA)* mX), dims=1); #<! Is there a `~` equivalent in Julia?
        vClusterId=dropdims(mClusterId, dims=1); # to be able to access it later

        for jj = 1:numClusters
            mA[:, jj] = mean( mX[:, vClusterId .== jj ], dims=2 );
        end
    end

    mA = mA[:, 1] .+ transpose(mA[:, end]);

    return mA
end

I call the function from a main script like this:

using Statistics
using LinearAlgebra
using Random # for randperm
include("test.jl");
mA=test();

I get the same result (NaNs) in the REPL.

The problem is with vClusterId and this line :
mA[:, jj] = mean( mX[:, vClusterId .== jj ], dims=2 );

julia> typeof(vClusterId)
Array{CartesianIndex{2},1}
julia> typeof(jj)
Int64
julia> jj=1; any(vClusterId .== jj)
false

so you are taking the mean of 0 values

julia> mean(Int[])
NaN

and so you set mA to be NaNs

change vClusterId=dropdims(mClusterId, dims=1);
to vClusterId = LinearIndices(dropdims(mClusterId, dims=1));
and your test function will operate.

1 Like

Thank you for your answer.
The original code was in Julia 0.5 and it worked fine there, the code was like

   for ii = 1:numIterations

        vMinDist, mClusterId(:) = findmin( transpose(sum(mA .^ 2, dims=1)) .- (2 .* transpose(mA)* mX), dims=1); 

        for jj = 1:numClusters
            mA[:, jj] = mean( mX[:, vClusterId .== jj ], dims=2 );
        end
    end

In Julia 1.1 I got an error, I thought it is because of dropdims. I am not familiar with the changes that has happend since that time. (diverging from MATLAB language)