We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello !
I have a question about the transpose of a 2D Array or Matrix. I wrote a short programm to explain my problem:
int [][] matrix = { {0, 0, 0},
{0, 1, 0},
{1, 1, 1} };
int [][] tmpMatrix = new int [3][3];
int [][] newMatrix = new int [3][3];
void setup() {
size(800, 600);
background(0);
tmpMatrix = matrix;
}
void draw() {
drawMatrix(newMatrix);
for (int j = 0; j<3; j++) {
for (int i = 0; i<3; i++) {
**newMatrix[j][i]**=tmpMatrix[i][j];
}
print("\n");
}
drawMatrix(matrix);
drawMatrix(tmpMatrix);
drawMatrix(newMatrix);
noLoop();
}
void drawMatrix(int [][] matrix) {
for (int j = 0; j<3; j++) {
print("\n");
for (int i = 0; i<3; i++) {
print(matrix[j][i]);
}
}
print("\n");
}
So this programm works fine and I get the transpose of the Matrix in "newMatrix".
But when I change the variable from "newMatrix" into "matrix" (I mean inside of the two for loops) the transposed matrix is wrong !
I don't understand what is the problem here.
Thank you a lot !
Answers
doesn't do what you think it does. this creates a reference between the two things, so now tmpMatrix isn't a copy of matrix, it's the exact same thing
Thanks ! That is what I thought too, but wasn't sure. So that is also the reason, why tmpMatrix changes in the for loops, right ? So this is not a new variable, but only a new varible name.
So, behind the variable names a and b in your example is same reference (or address) ?
But how can I copy only the value ?
double nested loop... like line 19 but without swapping i and j
stealing this from stack overflow:
http://www.journaldev.com/753/how-to-copy-arrays-in-java
not sure how they work with 2d arrays
Thanks a lot. Have a nice weekend.
I've created a utility function which copies the whole content of a 2D-Array (Matrix) to another 1 based on arrayCopy(): :\">
https://Processing.org/reference/arrayCopy_.html
You can see its console output online as well: :bz
https://OpenProcessing.org/sketch/496288
However you need to click at the right bottom icon in order to open the output console though: :-\"
Wow ! Nice. Thank you. This helps me a lot.