Skip to content
Advertisement

How do I create a matrix (values possibly empty) from columns and rows?

I have a table that contains actual data as well as empty cells. I want to parse it programatically but have some trouble doing so.

Example:

A E
B
C G
H

I also have an array of rows and columns, like:

rows columns
{
{A; E}
{B}
{C; G}
{H}
}
{
{A; B; C}
{E; G; H}
}

With this data, would it be possible to generate a matrix like the one below,essentially replacing the empty cells with 0s?

{
    {A; E}
    {B; 0}
    {C; G}
    {O; H}
}

The programming language doesn’t matter. I’ve attempted unsuccessfully with Dart, but I am open to any answers and know a few programming languages, python, or even better, pseudocode works.

I’ve came up with this but couldn’t really wrap my head around it. This doesn’t work, throws out of range errors, and I don’t think it’d be the best implementation.

void main() {
  produceTable();
}

void produceTable() {
  var columns = [
    ["A", "B", "C"],
    ["E", "G", "H"]
  ];
  var rows = [
    ["A", "E"],
    ["B"],
    ["C", "G"],
    ["H"]
  ];

  var table = List.generate(2, (index) => List.generate(4, (_) => "0"));
  int x = 0;
  int y = 0;
  int i = 0;
  for (int tableX = 0; tableX < table.length; tableX++) {
    for (var tableY = 0; tableY < table[tableX].length; tableY++) {
      print('x$x y$y');
      if (rows[x][y] == columns[y][x]) {
        table[tableX][tableY] = rows[x][y];
        if (x < rows.length - 1) {
          x++;
        } else {
          y++;
          x = 0;
        }
      }
    }
  }

  print(table);
}

P. S.: if there’s a name for this problem, I suppose others had came across this before, could you tell me? I searched for a while but couldn’t find a thing.

Advertisement

Answer

Considering the minimum requirment, where the data in the incomplete column can not be repeated. In this case we can easily fill the table using python with numpy module:

import numpy as np

A, B, C, E, G, H = 1, 2, 3, 4, 5, 6
rows = np.array([[A, E], [B], [C, G], [H]])
columns = np.array([[A, B, C], [E, G, H]])

table_vertical_len = len(rows)
table_horizontal_len = len(columns)

table = np.zeros((table_vertical_len, table_horizontal_len), dtype=float)

# fill table
for pos, each_row in enumerate(rows):
    if len(each_row) == table_horizontal_len:
        table[pos] = each_row
    else:
        for v in each_row:
            table[pos, np.where(columns==v)[0].item()] = v

print(table)

Also note that the data are assumed to be float number, otherwise you can only use specialized moudle to read directly from the file.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement