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

Confused when assign/add a block matrix

Tags: None
(comma "," separated)
zhanxw
Registered Member
Posts
17
Karma
0
In the example below, I tried to assign/add a block matrix (using .block() method) to a regular matrix.
When the dimensions of the matrix on both sides of the assignment, Eigen does not report errors nor crash.
My question:
(1) is this the expected behavior of Eigen?
(2) when assign/add a block matrix, should I always use .block() method on the lefthand side of the statement?
Thanks.

Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cassert>
#include <iostream>
#include "eigen/Eigen/Core"
#include "eigen/Eigen/Eigenvalues"

using namespace std;

int main(int argc, char** argv) {
  Eigen::MatrixXf a(4, 2);
  Eigen::MatrixXf b(6, 2);
  Eigen::MatrixXf c(6, 2);

  for (int i = 0; i < 4; ++i) {
    for (int j = 0; j < 2; ++j) {
      a(i, j) = i * 2 + j;
    }
  }
  std::cout << a << "\n\n";

  for (int i = 0; i < 6; ++i) {
    for (int j = 0; j < 2; ++j) {
      b(i, j) = i * 2 + j + 100;
      c(i, j) = i * 2 + j + 100;
    }
  }
  std::cout << b << "\n\n";

  std::cout << "wrong result! - expect [ 6 x 2 ]\n";
  b.noalias() += a.block(0, 0, 2, 2);
  std::cout << b << "\n\n";

  b = c;
  std::cout << "wrong result! - expect [6 x 2 ]\n";
  b += a.block(0, 0, 2, 2);
  std::cout << b << "\n";

  b = c;
  std::cout << "wrong result! - expect dimension mismatches and crash\n";
  b += a;
  std::cout << b << "\n";

  b = c;
  std::cout << "correct result!\n";
  b.block(0, 0, 2, 2).noalias() += a.block(0, 0, 2, 2);
  std::cout << b << "\n";

  b = c;
  std::cout << "wrong result! - expect dimension mismatches, crash and the same results as before\n";
  b += a;
  std::cout << b << "\n";

  return 0;
}


Outputs
0 1
2 3
4 5
6 7

100 101
102 103
104 105
106 107
108 109
110 111

wrong result! - expect [ 6 x 2 ]
-7.64442e-22 1
2 3

wrong result! - expect [6 x 2 ]
0 2
2 6
wrong result! - expect dimension mismatches and crash
1.48662e-38 -nan
2 3
4 5
6 7
correct result!
100 102
104 106
104 105
106 107
108 109
110 111
wrong result! - expect dimension mismatches, crash and the same results as before
1.48662e-38 -nan
2 6
4 10
6 14
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
Compile without -DNDEBUG to get the asserts on size-mismatches.


Bookmarks



Who is online

Registered users: abc72656, Bing [Bot], daret, Google [Bot], Sogou [Bot], Yahoo [Bot]