jxk22
jxk22

Reputation: 31

How to exchange one specific value in an array in Julia?

I'm pretty new to Julia, so this is probably a pretty easy question. I want to create a vector and exchange a given value with a new given value.

This is how it would work in Java, but I can't find a solution for Julia. Do I have to copy the array first? I'm pretty clueless..

function sorted_exchange(v::Array{Int64,1}, in::Int64, out::Int64)
    i=1
    while v[i]!=out
        i+=1
    end
    v[i]=in
    return v
end

The program runs but just returns the "old" vector. Example: sorted_exchange([1,2,3],4,3), expected:[1,2,4], actual:[1,2,3]

Upvotes: 1

Views: 1012

Answers (2)

DNF
DNF

Reputation: 12653

There's a nice built-in function for this: replace or its in-place version: replace!:

julia> v = [1,2,3];

julia> replace!(v, 3=>4);

julia> v
3-element Array{Int64,1}:
 1
 2
 4

The code you have posted seems to work fine, though it does something slightly different. Your code only replaces the first instance of 3, while replace! replaces every instance. If you just want the first instance to be replaced you can write:

julia> v = [1,2,3,5,3,5];

julia> replace!(v, 3=>4; count=1)
6-element Array{Int64,1}:
 1
 2
 4
 5
 3
 5

Upvotes: 4

Nils Gudat
Nils Gudat

Reputation: 13800

You can find the value you want to replace using findall:

a = [1, 2, 5]
findall(isequal(5), a) # returns 3, the index of the 5 in a

and use that to replace the value

a[findall(isequal(5), a)] .= 6
a # returns [1, 2, 6]

Upvotes: 3

Related Questions