AssertionError

i have this piece of code:

MAT=[1 0;0 2]
n=count(!iszero,MAT)
n0=MAT[1:n]
@assert n0 == ones(n)

i ran into an unexpected assertion error for this part, apparently @assertdidn’t evaluate the assert code line for some reason, and i’m getting for this part:

AssertionError: n0 == ones(n)

Stacktrace:
 [1] top-level scope at In[15]:4

Try

MAT=[1 0;0 2]
n=count(!iszero,MAT)
n0=MAT[1:n]
@show n0
@show ones(n)
@assert n0 == ones(n)
1 Like

your two things aren’t ==, @assert for sure does evaluate before comparison:

julia> @assert [1,1,1] == ones(2)
ERROR: AssertionError: [1, 1, 1] == ones(2)
Stacktrace:
 [1] top-level scope at REPL[2]:1

julia> @assert [1,1,1] == ones(3)

still got the same assertion error:

n0 = [1, 0]
ones(n) = [1.0, 1.0]

AssertionError: n0 == ones(n)

Stacktrace:
 [1] top-level scope at In[16]:6

Of course it still throws the same assertion error. The @show statements are only there to make it easier to see why the assertion fails. (Look at the last element of each vector.)

1 Like

yes the last element of the two vectors are differents, then how can i make the vector==ones(r)in this case??

You will need to rethink how you compute n. If this is a homework assignment, then read the text very carefully. Right now you compute n to be the number of nonzeros in all of MAT. Was this what you were asked to do? Maybe the task was to count only at the beginning of MAT?

2 Likes

it’s not a homework actually it’s a piece of code from a big code where i’m having problems with, and yes n is the number of nonzeros in all of MAT , after computing n0 i want to make it as ones(n)

What do you mean by “it” in this sentence? Do you want to modify the first n elements of MAT? Here’s how to do that:

julia> MAT[1:n] .= 1;

julia> MAT
2×2 Array{Int64,2}:
 1  0
 1  2

i mean want to make n0 equals to ones(n)

n0== ones(n)

Oh. I see. That can be done with:

n0 = ones(n)

after which you can try

n0 == ones(n) # returns `true`