Write a two-dimensional array (matrix) to text files?

Hi everyone!
I am an absolute beginner in Processing.
I’m trying to figuring how to write a 12x12 two-dimensional array of integers to a .txt file but I don’t have any idea…
Can someone please suggest me how?
The full code is actually quite long and I don’t think it’s really important (just long, boring maths), but here’s the latest few lines where I finally print everything to the console:

  for (int i = 0; i < 12; i ++) { 
   for (int j = 0; j < 12; j ++) { 
     print (matrixpos[j][i] + 1 + " "); 
     if (j==11) {
println(); 
        }
     }
  }

…I guess the saving part should be added here, but again, I’m a beginner so I’m not sure…

Thank you all for help, any idea will be really appreciated.
See ya!
A.

1 Like

Hello,

Consider:
https://processing.org/tutorials/data/
https://processing.org/reference/Table.html

Resources

I encourage you to review the resources available here:

:)

1 Like

This is what I’ve come up w/: :nerd_face:

/**
 * Save & Load TSV as int[][] (v1.0.1)
 * GoToLoop (2020/Apr/11)
 *
 * https://Discourse.Processing.org/t/
 * write-a-two-dimensional-array-matrix-to-text-files/19674/3
 */

static final TableType TABLE_TYPE = TableType.TSV;
static final String FILENAME = "Matrix" + '.' + TABLE_TYPE.EXT;
static final int[] COL_TYPES = { Table.INT, Table.INT, Table.INT };
static final int ROWS = 12, COLS = 12;

int[][] matrixPos = new int[ROWS][COLS];

void setup() {
  // Save matrixPos[][] to disk:
  final String fullPath = dataPath(FILENAME);
  final String[] arr1d = intArr2dToStrArr1d(matrixPos, TABLE_TYPE.SEP);
  saveStrings(fullPath, arr1d);

  // Load matrixPos[][] from disk:
  final Table t = loadTable(FILENAME, TABLE_TYPE.EXT);
  t.setColumnTypes(COL_TYPES);
  matrixPos = tableToIntArr2d(t);

  // Display matrixPos[][]'s content:
  for (final int[] arr : matrixPos)  println(str(arr));

  exit();
}

static final String[] intArr2dToStrArr1d(final int[][] arr2d, final char sep) {
  if (arr2d == null || arr2d.length == 0)  return new String[0];

  final int len = arr2d.length;
  final String[] arr1d = new String[len];

  for (int i = 0; i < len; arr1d[i] = join(str(arr2d[i++]), sep));

  return arr1d;
}

static final int[][] tableToIntArr2d(final Table t) {
  if (t == null || t.getRowCount() == 0)  return new int[0][0];

  final int rows = t.getRowCount(), arr2d[][] = new int[rows][];

  for (int i = 0; i < rows; arr2d[i] = t.getIntRow(i++));

  return arr2d;
}

static enum TableType {
  CSV("csv", ','), TSV("tsv", '\t');

  final String EXT;
  final char SEP;

  TableType(final String ext, final char sep) {
    EXT = ext;
    SEP = sep;
  }
}

I’ve relied on many Processing functions, such as: :sunglasses:

1 Like

Done!
I was not familiar with the table object.
Thank you all for your help and for every suggestion.

2 Likes