D. Sukhov
D. Sukhov

Reputation: 361

Append in Julia

I am new to Julia. A was curious how do I append values. I want b to grow every time the boolian value is True. And then to output its size.

function f(img_deformed, img)
    s = size(img)[1]
    for i in range(1,s,step=1)
        for j in range(1,s,step=1)
            b = img_deformed[i,j] == img[i,j]           
        end
    end
    return b
end

Upvotes: 3

Views: 570

Answers (1)

Aaron D. Carta
Aaron D. Carta

Reputation: 71

If you want b to be a vector that tracks the number of times that the equality in your for loop is satisfied, you can use push!:

function f(img_deformed, img)
    s = size(img)[1]
    b = Vector{Bool}() # Can also use Bool[]
    for i in range(1,s,step=1)
        for j in range(1,s,step=1)
            if img_deformed[i,j] == img[i,j]
               push!(b, true)
            end           
        end
    end
    return length(b)
end

However, if all you really care about is the number of trues, it's easier (and almost certainly better) to just use b as a counter:

function f(img_deformed, img)
    s = size(img)[1]
    b = 0
    for i in range(1,s,step=1)
        for j in range(1,s,step=1)
            if img_deformed[i,j] == img[i,j]
               b += 1
            end          
        end
    end
    return b
end

Some minor style points: s = size(img)[1] is equivalent to s = size(img, 1), and the range(1, s, step=1) is equivalent to 1:s, so your code could be written slightly more simply as

function f(img_deformed, img)
    s = size(img, 1)
    b = 0
    r = 1:s
    for i in r
        for j in r
            if img_deformed[i,j] == img[i,j]
               b += 1
            end          
        end
    end
    return b
end

However, that doesn't address a potential mistake in the original code: unless you know that img will always be a square matrix, using the same range (1:s) for both for loops is not guaranteed to be correct. To avoid this problem, you can use axes:

function f(img_deformed, img)
    b = 0
    for j in axes(img, 2)
        for i in axes(img, 1)
            if img_deformed[i,j] == img[i,j]
               b += 1
            end          
        end
    end
    return b
end

Notice here that I've chosen to loop over the columns first; this is a good practice in Julia, since arrays are stored in column-major order (see the explanation here from the manual).

Note also that using img to control the values that we loop over implicitly assumes that size(img) == size(img_deformed). Without knowing more about what this function is intended for, it's hard to suggest how to deal with that, but if you can assume that the two matrices should be the same size, you can add a check at the top of f(), e.g.

function f(img_deformed, img)
   @assert size(img) == size(img_deformed)
   # rest of code is the same
end

Upvotes: 3

Related Questions