Multidimensional array initialization

I’m currently initializing with the following code:

                const fd2: [16][16]@Vector(4, f32) = .{
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                    [_]@Vector(4, f32){.{1.0, 1.0, 0.0, 1.0}} ** 16,
                };

Is there a more compact way to do this? Preferably with fewer @Vector declarations on the right hand side?

Thanks.

    const V = @Vector(4, f32);
    const one: [1]V = .{.{ 1.0, 1.0, 0.0, 1.0 }};
    const row: [1][16]V = .{one ** 16};
    const rows: [16][16]V = row ** 16;
3 Likes

Certainly more compact, but is there no way to do this without the intermediate variables?

I guess I could use @as, but that’s still sorta the same thing.

I was looking for something like:
const fd2: [16][16]@Vector(4, f32) = .{.{.{1.0, 1.0, 0.0, 1.0}**16}**16}; // This doesn't actually work

1 Like

Looks like you were really close. Took me a few minutes but this compiles

const fd2: [16][16]@Vector(4, f32) = 
    .{.{.{ 1.0, 1.0, 0.0, 1.0 }} ** 16} ** 16;

I think the only difference was removing the outer braces.

7 Likes

On the latest master branch you can use @splat to initialize arrays.

const fd: [16][16]@Vector(4, f32) = @splat(@splat(.{ 1, 1, 0, 1 }));
10 Likes

I wish I could mark both the answers as correct.

However, I’m going to mark @Travis answer as the correct one as it works in Zig as it stands. In addition, getting it right is less intuitive and isn’t documented very well anywhere.

@splat() was approved literally 3 days ago. I’ll start making use of it once it hits release, though. That’s a lot nicer. Thanks for pointing that out @T0bee .

2 Likes