Skip to content

Apply function row/column-wise #154

@npiccolotto

Description

@npiccolotto

Hello,

thanks for the great library, I use it quite often in my work. Something I didn't find in the API and thus copy around my projects is an apply function? Like R's apply or numpy's apply_along_axis.

It seems like a simple function, my implementation is basically

function apply(M, fun, axis = 1) {
  // axis = 0: apply and collapse along cols (= output length is # rows)
  // axis = 1: apply and collapse along rows (= output length is # cols)
  const collapseRows = axis === 1;
  const n = collapseRows ? M.columns : M.rows;
  const result = [];
  for (let i = 0; i < n; i++) {
    const x = collapseRows ? M.getColumn(i) : M.getRow(i);
    result.push(fun(x));
  }
  return Matrix.rowVector(result); // NOTE could also be columnVector depending on `axis`, I just never wanted one...
}

Would this be something that you would consider adding to your library?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions