Let A=[x1,x2,x3,y1,y2,y3,y4]
I want to replace everything after y1 in the arrays A:
A=[x1,x2,x3,y1,y1,y1,y1]
I tried
for i in eachindex(A)
if A[i]==y1
for j in i:length(A)
A[j]=y1
end
end
end
but it seems complicate, is there any other way to do it simple?
CodePudding user response:
If you just want to fix your own code instead of a different approach:
for i in eachindex(A)
if A[i]==y1
for j in i 1:lastindex(A)
A[j]=y1
end
break # this is important
end
end
The break
statement jumps out of the current loop. It should also be very efficient. I also replaced length(A)
with lastindex(A)
to make it more generic, since you already use eachindex
.
CodePudding user response:
Is this what you want? In the example I assume that your y1
is 1
.
julia> A = [5, 4, 3, 1, 2, 7, 8]
7-element Vector{Int64}:
5
4
3
1
2
7
8
julia> loc = findfirst(==(1), A)
4
julia> isnothing(A) || (A[loc:end] .= 1);
julia> A
7-element Vector{Int64}:
5
4
3
1
1
1
1