Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add matrix iteration like JS does #1883

Closed
mightypenguin opened this issue Jun 11, 2020 · 2 comments
Closed

Add matrix iteration like JS does #1883

mightypenguin opened this issue Jun 11, 2020 · 2 comments
Labels

Comments

@mightypenguin
Copy link

For multi dimensional arrays in JS this is how forEach works:
e.g.
let ar1 = [1];
let ar2 = [2];
let arr = [ ar1, ar2 ];

arr.forEach( el => { /** el will equal ar1 or ar2 array object */ } );

In Mathjs the matrix().forEach returns the deepest/innermost element:
e.g.
let ar1 = [1];
let ar2 = [2];
let arr = matrix([ ar1, ar2 ]);

arr.forEach( el => { /** el will equal the number 1 or 2. NOT [1] or [2] */ } );

Right now if I want to loop through the element with the JS behavior I have to grab the hidden matrix array member "_data" which I assume is "wrong".

Please add some support to allow JS style looping through matrix elements.
This could be "easily" done by adding an optional/default parameter to the matrix.forEach method. Maybe "useJSBehavior" defaulted to false?

e.g.
arr.forEach( el => { /** el will equal the array [1] or [2]. */ }, true);

@josdejong
Copy link
Owner

The idea of the Matrix classes is that they handle multi dimensional arrays. The map and forEach methods indeed loop over all elements and provide you with the index of the element which is typically not a single number but for example the row and column index. You should not see a Matrix as an Array containing Arrays, but really as a matrix with cells having a row and column index. The current implementation internally uses nested arrays but that could theoretically change, and there should be no need to utilize that. For example SparseMatrix does have a different internal structure without nested arrays.

If you do need an array containing arrays, I think it's best to simply use a plain Array for that (or rethink your approach ;) ).

@cshaa
Copy link
Collaborator

cshaa commented May 24, 2021

This will be probably solved by #2177. Then you could do:

for (const row of rows(m)) {
  // here, row is [1] or [2]
}

Repository owner locked and limited conversation to collaborators Aug 17, 2022
@josdejong josdejong converted this issue into discussion #2656 Aug 17, 2022

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
Projects
None yet
Development

No branches or pull requests

3 participants