Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set values of a 2D array using specific coordinates

Disclaimer: This could apply to any programming langage but I am using C++, so I’m using the C++ tag.

I have an array of an xyz structure:

struct xyz {
    float x, y, z;
};

In the array I create, at first I only initialize the x and y as I know the z value only later in the code like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

size = Width * Height;    
Cloud = new xyz[size];

// Remplissage des indices de Pixels
for (int i = 0; i < size; i++)
{
    Cloud[i].x = i % Width;

    Cloud[i].y = i / Width;
}   

};

This results in an array that looks like that:

x; y; z
0; 0; 0
1; 0; 0
2; 0; 0
3; 0; 0
0; 1; 0
1; 1; 0
2; 1; 0
3; 1; 0
0; 2; 0
1; 2; 0
2; 2; 0
3; 2; 0

So after that, I want to set a z value for such x and y values but I don’t know how to do that in an effective way (I don’t want to use a loop that goes through my whole array until I find the right x and y set).

My problem I guess is how to do the inverse math of Cloud[i].x = i % Width and Cloud[i].y = i / Width into something to do Cloud[??].z = someValue.

Thank you in advance!

>Solution :

That is simple mathematics. If you have x and y and want to know the index to address the z-value later, then you may calculate "y * width + x".

So:

Cloud[y * Width + x].z = zValue; 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading