Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

iteration - Julia, syntax to use @views in a function

I would like to build a function, that iterates through values of a Julia "zip" file and substitutes some values in a large 3d array. In a previous help someone wise suggested the use of @view and I quite like the idea of writing back to the original section of the array rather than making a copy. If this is good method (happy to take advice), I can't figure out the correct syntax for the function, that exploits @view. This is a demo:

Original code, which works well, will be many more in final application

(@view Pop[end, :, 1])[findall(x -> x==33, Pop[end, :, 1])] .= 3
(@view Pop[end, :, 1])[findall(x -> x==44, Pop[end, :, 1])] .= 4

It simply substitutes 33 -> 3, and 44 -> 4 in the array Pop[end, :, 1]

So I produce the zip file:

Orig = [44, 33];
NewS = [4 , 3];
ResetZip = zip(Orig,NewS)

Then produce the function:

## Function to reset status numbers back from 44 and 33 to 4 and 3
function ResetState(Arr1, Orig, NewS)
    Arr1[findall(x -> x==Orig, Arr1)] .= NewS
end

Then try to execute the function iteratively over values of ResetZip

for (Orig, NewS) = ResetZip
    ResetState(@view (Pop[end, :, 1]), Orig, NewS)
end

but I get this error

ERROR: LoadError: ArgumentError: Invalid use of @view macro: argument must be a reference expression A[...].

So I've got something wrong in the syntax. My question is, where do I put the @view to get the syntax correct, to be able to use it, and iterate over values of the zip file? Thx. J

question from:https://stackoverflow.com/questions/65889525/julia-syntax-to-use-views-in-a-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@MattB.'s answer explains the macro issue, but you are severely over-complicating things in the first place. There is no need to use the @view macro like this. Instead of

(@view Pop[end, :, 1])[findall(x -> x==33, Pop[end, :, 1])] .= 3

you can write

Pop[end, findall(x -> x==33, Pop[end, :, 1]), 1] .= 3

But that's too complicated too. Instead of this, you can write

Pop[end, Pop[end, :, 1].==33, 1] .= 3

But this is also needlessly complicated. What you really should do is to use the replace! function. Though, then you have to use views again:

replace!(@view(Pop[end, :, 1]), 3=>33)

And now you can even do both replacements at the same time:

replace!(@view(Pop[end, :, 1]), 33=>3, 44=>4)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...