0

I am trying to write a function in processing.js that takes as an input an array list with 4 lists of class int[] each containing 4 elements. This is how I am representing a matrix, with each list in the array list representing a row. Index 0 of the Array list is the top row and index 3 of the array list it the bottom row. I want to write a function to transpose this array list, but I have run into a snag. here is my code so far (note: Z is a 4x4 arraylist filled with zeros):

ArrayList<int[]> Transpose(ArrayList<int[]> M){
  ArrayList<int[]> A=Z;
  for (int q=0; q<4; q++){
    int[] atemp={};
    for (int p=0; p<4; p++){
      int[] mtemp=M.get(p);
      int i=mtemp[q];
      append(atemp,i);
    }
    A.add(atemp);
  }
  return A;
}

My problem seems to be happen when I try to append i to atemp. When I print out the atemp.length right before it is added to A, it prints a length of 0. I am not sure why atemp has remained empty, and I am wondering if anyone can help me understand what is happening and how to fix it.

Wickerbough
  • 365
  • 1
  • 4
  • 15
Joshua
  • 11
  • 1
    I actually need to change the `ArrayList A=Z;` line to `ArrayList A=new ArrayList();` so it returns a 4x4 array list instead of an 8x4, but i still have the same issue. – Joshua Apr 06 '21 at 16:13

2 Answers2

0

I'm no JavaScript expert (you tagged this question with Java, that's why I looked) but I think you should create an array like this in JS:

int[] atemp = [];

With the curly braces you might be creating an object?

Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
0

You've already figured out that you need to allocate A as a new ArrayList as opposed to simply making another reference to an existing one.

Additionally, if you simply need a 4x4 transformation matrix in Processing.js use the PMatrix3D class which already has transpose() implemented:

PMatrix3D A = new PMatrix3D();
// modify A as a test
A.translate(10, 20, 30);
println("A:");
A.print();
// clone A
PMatrix3D Z = A.get();
Z.transpose();
println("Z:");
Z.print();

which should output:

A:
 01.0000  00.0000  00.0000  10.0000
 00.0000  01.0000  00.0000  20.0000
 00.0000  00.0000  01.0000  30.0000
 00.0000  00.0000  00.0000  01.0000

Z:
 01.0000  00.0000  00.0000  00.0000
 00.0000  01.0000  00.0000  00.0000
 00.0000  00.0000  01.0000  00.0000
 10.0000  20.0000  30.0000  01.0000

(You can use applyMatrix() to apply the transformation to the renderer).

Bare in mind ProcessingJS is no longer maintained.

George Profenza
  • 50,687
  • 19
  • 144
  • 218