For loop : mixing iterator with argument of a function

Hello everyone.

I am using Julia 1.7.3 with Jupyter Lab, and I have this code (which is partially taken from this link : Converting image colors · ColorSchemeTools) :


using FileIO, ColorSchemes, ColorSchemeTools, Images

img = load("julia-logo-square.png")
img_rgb = RGB.(img)

convertedimage_4 = convert_to_scheme(ColorSchemes.PiYG_4, img_rgb)
convertedimage_5 = convert_to_scheme(ColorSchemes.PiYG_5, img_rgb)
convertedimage_6 = convert_to_scheme(ColorSchemes.PiYG_6, img_rgb)

IJulia.display(convertedimage_4)
IJulia.display(convertedimage_5)
IJulia.display(convertedimage_6)
    

However, instead of typing :

convertedimage_4 = convert_to_scheme(ColorSchemes.PiYG_4, img_rgb)
convertedimage_5 = convert_to_scheme(ColorSchemes.PiYG_5, img_rgb)
convertedimage_6 = convert_to_scheme(ColorSchemes.PiYG_6, img_rgb)

IJulia.display(convertedimage_4)
IJulia.display(convertedimage_5)
IJulia.display(convertedimage_6)
    

I’d like to execute the following pseudo-code :

for i in 4:6
    convertedimage_i = convert_to_scheme(ColorSchemes.PiYG_i, img_rgb)
    IJulia.display(convertedimage_i)
end

where the iterator i will go from 4 to 6 of course.

This is easier when done with strings, but in this situation, I am a bit stuck.

Anybody have an idea on how to solve this (it’s basic I think, but I’m not sure how to do this in Julia) ?

The way you programmatically access properties is with getproperty, which accepts Symbols.
I.e., ColorSchemes.PiYG_1 === getproperty(ColorSchemes, :PiYG_1).
So you can do:

for i in 4:6
    scheme = getproperty(ColorSchemes, Symbol("PiYG_$i"))
    convertedimage_i = convert_to_scheme(scheme, img_rgb)
    IJulia.display(convertedimage_i)
end
2 Likes

I expect that the desired assignment is to variables such as convertedimage_4 etc. In that case:

i = 4
v = Symbol("convertedimage_$i")
cs = getfield(ColorSchemes, Symbol("PiYG_$i"))
@eval ($v)=($cs)

It’s not really faster or anything, but I like this syntax, aesthetically:

Symbol(:PiYG_, i)
3 Likes

Perfect ! That worked. Thanks a lot !