This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Matrix replace function

Tags: None
(comma "," separated)
User avatar
Koldo
Registered Member
Posts
16
Karma
0

Matrix replace function

Mon Mar 19, 2012 8:40 am
Hello all

Do you know if it exists a function to replace values inside a Matrix?.

For example a naive implementation for a MatrixXi would be:

Code: Select all
void Replace(MatrixXi &mat, int find, int replace)
{
   for (int r = 0; r < mat.rows(); ++r)
      for (int c = 0; c < mat.cols(); ++c)
         if (mat(r, c) == find)
            mat(r, c) = replace;
}


Best regards
Koldo
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Matrix replace function

Mon Mar 19, 2012 8:45 pm
you can use std::replace:

MatrixXi A;
std::replace(A.data(), A.data()+A.size(), key, newval);


or (more general but perhaps less efficient in this case):

A = (A.array()==key).select(newval, A);
User avatar
Koldo
Registered Member
Posts
16
Karma
0

Re: Matrix replace function

Tue Mar 20, 2012 6:35 am
Thank you Gael!


Bookmarks



Who is online

Registered users: Bing [Bot], claydoh, Google [Bot], rblackwell, Yahoo [Bot]