Build a new matrix made of some source matrix rows given a row index vector - eigen3

I want to build a new matrix made of some source matrix rows given a vector of non consecutive indexes.
Namely, I'd like a row() function which take a list of indexes and returns the list of rows stored in a new matrix :
VectorXi v = VectorXi::LinSpaced( 4, 10, 13);
MatrixXi m = v.rowwise().replicate( 4 );
VectorXi r1 ( ( VectorXi(3) << 0, 3, 1 ).finished() );
// Here is some pseudo code to create the desired matrix N :
MatrixXi N = m.row(r1);
cout << "m = " << m << endl;
cout << "r1 = " << r1 << endl;
cout << "N = " << N << endl;
Desired output :
m =
10 10 10 10
11 11 11 11
12 12 12 12
13 13 13 13
r1 =
0
3
1
N =
10 10 10 10
13 13 13 13
11 11 11 11
Thanks a lot for helping.
Sylvain

With the development branch and (at least) C++11 enabled, you can write:
Eigen::MatrixXi N = m(r1,Eigen::all);
This is similar to the Matlab syntax:
N = m(r1, :);
You can also pass {x,...}-lists directly, or anything that behaves like an std::vector<int> (must provide a size() function and an operator[] and return an integral type), e.g.:
std::vector<int> c2{{3,0}};
std::cout << "m({2,1},c2) = \n" << m({2,1}, c2) << '\n';
These expressions are writable (assuming m itself is writable):
m({2,1}, c2) = Eigen::Matrix2i{{1,2},{3,4}};
std::cout << m << '\n';
Godbolt demo: https://godbolt.org/z/cjacOY

Related

How the 11th element got added into array if the decalred array is arr[10]?

The code
using namespace std;
int main ()
{
int arr[10], n, i, sum = 0, pro = 1;
cout << "Enter the size of the array : ";
cin >> n;
cout << "\nEnter the elements of the array : ";
for (i = 0; i < n; i++)
cin >> arr[i];
for (i = 0; i < n; i++)
{
sum += arr[i];
pro *= arr[i];
}
cout << "\nSum of array elements : " << sum;
cout << "\nProduct of array elements : " << pro;
return 0;
}
Here, I did not understand how the 11 can be given as input to get the sum and the product
Output sample
Enter the size of the array : 11
Enter the elements of the array : 11 10 9 8 7 6 5 4 3 2 1
Sum of array elements : 66
Product of array elements : 39916800
That's because arrays are actually pointers.
When you create an array, you are basically telling the compiler to reserve enough space to store all elements of the array. When you access the 11th element of the array you are accessing part of the memory that is not reserved for your array, which I think is considered undefined behaviour.
Try the following:
int a = 24;
int b = 24;
int c = 24;
int d = 24;
int arr[0];
int e = 24;
int f = 24;
int g = 24;
int h = 24;
cout << arr[2];
You will probably see the number 24 printed to the screen because you are accessing some memory that is reserved for other variables.
The positions of an array start at 0, so if you start counting from 0, the element in position 10 is on 11

Most efficient way to find an intersection between two sets of numbers encoded with bitwise operations

Given two sets of numbers encoded with bitwise operations (using 6 bits for number):
a = {12,20,21,24,31}
b = {13,18,24,28,35}
Intersection -> a ∩ b = {24}
unsigned int a = 0;
a |= (12 | 20 << 6 | 21 << 12 | 24 << 18 | 31 << 24);
unsigned int b = 0;
b |= (13 | 18 << 6 | 24 << 12 | 28 << 18 | 35 << 24);
What is the fastest way to find out, if there is at least one number in common between the sets?
This is just an example, but you can have common numbers in any position.
#include <stdint.h>
#include <limits.h>
typedef unsigned int SetType;
#define FieldWidth 6 // Number of bits per field.
#define NumberOfFields (sizeof(SetType) * CHAR_BIT / FieldWidth)
// Return non-zero iff some element is in both a and b.
int IsIntersectionNonEmpty(SetType a, SetType b)
{
// Create masks with a bit set for each element an input set.
uint64_t A = 0, B = 0;
for (int i = 0; i < NumberOfFields; ++i)
{
A |= UINT64_C(1) << (a >> i*6 & 0x3f);
B |= UINT64_C(1) << (b >> i*6 & 0x3f);
/* ">> i*6" moves field i to the low bits.
"& 0x3f" isolates that six-bit field.
"UINT64_C(1) << …" generates a 1 bit in that position.
*/
}
/* Bitwise AND A and B to see if they have a bit in common, then
convert that to 1 or 0.
*/
return !! (A & B);
}
Maybe not the absolute fastest, but I'd XOR a with b, and see if the result has any six-bit all-zeros pattern in any of your 5 positions. Then shift one of them by 6 bits and repeat up to 4 more times if needed.
Here's a somewhat faster version of my solution above; instead of shifting left and right, just rotate:
int leftRotate(unsigned int n, unsigned int d)
{
return (n << d)|(n >> (32 - d));
}
// Return non-zero iff some element is in both a and b.
int IsIntersectionNonEmpty(unsigned int a, unsigned int b)
{
for (int i = 0; i < 5; i++) {
unsigned int matches = leftRotate(a, i*6) ^ b;
for (int j = 0; j < 5; j++) {
unsigned int testval = 0x3f << j*6;
if (matches & testval == testval)
return 1; // success
}
}
return 0;
}
5 instructions in the outer loop, 3 in the inner * 5, so 20 total, times 5 loops, around 100 instructions total -- but as soon as it finds a match it returns. So if there are frequent matches it'll likely be faster than the #eric-postpischil version, but with no matches it'll be slower. On the other hand, his solution is likely auto-vectorizable with a smart compiler.
Well, thanks to everyone, but thank to the guy that posted the EL code, I do not know why he withdrew it.
Here we go, as fast as light:
#define EL(x) (UINT64_C(1) << (x))
unsigned int a = 0;
a |= (12 | 20 << 6 | 21 << 12 | 24 << 18 | 31 << 24);
unsigned int b = 0;
b |= (13 | 18 << 6 | 24 << 12 | 28 << 18 | 35 << 24);
unsigned int aa = EL(a & 0x00000003F) | EL((a & 0x000000FC0) >> 6) | EL((a & 0x3F000) >> 12) | EL((a & 0xFC0000) >> 18) | EL((a & 0x3F000000) >> 24);
unsigned int bb = EL(b & 0x00000003F) | EL((b & 0x000000FC0) >> 6) | EL((b & 0x3F000) >> 12) | EL((b & 0xFC0000) >> 18) | EL((b & 0x3F000000) >> 24);
anb = !! (aa & bb); // intersection

Finding closest power of 2 for any float at compile time

I need to scale all floats to [-1,1] range by dividing with closest higher power of 2. The code needs to be Q0.31 fixed-point, so no floats.
For example, 10.75 would be divided by 16, 20.91 by 32, 1000.17 by 1024, etc, all the way to 2^31.
I'd need the scaling to be done at compilation time.
For example:
#define PARAMETER1 10.0f // this could be changed in various builds
#define PARAMETER1_SCALE ( CALC_SCALE(PARAMETER1) )
#define float_to_fixed(x) ( (int)( (float)(x)*(float)0x80000000 ) )
int main()
{
int par1 = float_to_fixed( PARAMETER1/PARAMETER1_SCALE );
// use par1 here
// ...
// then descale using PARAMETER1_SCALE again
}
Is there a C macro CALC_SCALE which would calculate this?
How about this:
#include <math.h>
#define collapse(value) (value < 0 ? value / pow(2, ceil(log2(value * -1))) : value / pow(2, ceil(log2(value))))
int main() {
cout << collapse(10.75) << endl;
cout << collapse(20.91) << endl;
cout << collapse(-1) << endl;
cout << collapse(-2.5) << endl;
cout << collapse(5.7) << endl;
}
Output is:
0.671875
0.653438
-1
-0.625
0.7125
This does it:
#define CALC_SCALE ( x > 16 ? 32 : x > 8 ? 16 : x > 4 ? 8 : x > 2 ? 4 : x > 1 ? 2 : 1 )
At compile time:
int x = CALC_SCALE( 13 );
is compiled to:
int x = 16;
This can easily be changed to support floats.

efficient loop of a map within a map c++

I am attempting to find an efficient loop over a map data structure.
The map structure maps the following integers:
1 2, 2 3, 3 1, 4 1, 4 5, 5 3, 5 6, 5 7, 5 8, 6 4, 7 6, 8 9, 9 10
The resulting map looks as follows:
1| 2
2| 3
3| 1
4| 1 5
5| 3 6 7 8
6| 4
7| 6
8| 9
9| 10
Start : 4
Result :
1(1) 2(2) 5(1) 3(2) 6(2) 7(2) 8(2)
Can anybody suggest how to efficiently loop (possibly recursive method) so that, given a start of say 4, the result would be
1(1), 2(2), 5(1), 3(2), 6(2), 7(2), 8(2), 9(3), 10(4)
So the idea is to use each inner key, as an outer key, starting with a given outer key. With outer 4 for example, the inner keys are 5 and 1. So use 5 and 1 as outer keys to obtain inner keys (3 6 7 8) and (2), the process should continue mapping the inner keys to outer keys. A running total should be kept per "jump". So it probably resolves to a recursive problem rather than a loop.
The process should stop if either you reach the starting point, 4 in the above scenario, or there are no more inner keys, for example, 10 has no mapping.
The loop starting at line 44, only performs the above, up to two levels, which is inadequate.
#include <iostream>
#include <map>
#include <sstream>
int digit_count(int number) {
int digits = 0;
if (number < 0) digits = 1; // remove this line if '-' counts as a digit
while (number) {
number /= 10;
digits++;
}
return digits;
}
int main() {
int v1, v2;
std::map< int, std::map< int, int> > m;
std::istringstream stm {"1 2 2 3 3 1 4 1 4 5 5 3 5 6 5 7 5 8 6 4 7 6 8 9 9 10"};
while (stm >> v1 >> v2) {
m[v1];
m[v1][v2] = 1;
}
std::cout << "Map layout " << "\n";
std::string ss = "";
int dc = digit_count(m.rbegin()->first); // equals max number
for (const auto & p : m) {
std::cout << p.first << ss.append(" ", (dc - digit_count(p.first))) << "| ";
for (const auto & val : p.second)
std::cout << val.first << " ";
ss = "";
std::cout << "\n";
}
int start {4};
std::cout << "\nStart : " << start << "\n";
std::cout << "Result : " << "\n";
// efficient loop
for (const auto & e : m[start]) {
std::cout << e.first << "(" << e.second << ") ";
for (const auto & x : m[e.first])
std::cout << x.first << "(" << (e.second + x.second) << ") ";
}
std::cout << "\n";
return 0;
}
Any help would be much appreciated.
Took me a while, but I've answered my own question, and thought I'd update the post. The only way I could think of finding a solution was to create a recursive function. I don't think it is possible to achieve with loops. I didn't select Dijkstra's algorithm, since there are no weights to consider and the results of this recursive function serve as input to a red black tree where each node of the red black tree holds a hash table (unordered_map).
So the result of the query on the combined red black tree/hash table is Log n, to find the shortest path. The problem is providing the input, as you can see from below, is recursive and inefficient.
#include <iostream>
#include <map>
#include <sstream>
#include <set>
#include <vector>
#include <fstream>
int digit_count(int number) {
int digits = 0;
if (number < 0) digits = 1; // remove this line if '-' counts as a digit
while (number) {
number /= 10;
digits++;
}
return digits;
}
struct vertex {
int point;
mutable bool visited{false};
int id;
};
void clear_visited(std::map<int, vertex>& verteces) {
for (const auto & e : verteces) {
e.second.visited = false;
}
}
void traverse_graph(std::map<int, vertex>& verteces, const vertex & v, std::map< vertex, std::map< vertex, int> >& graph, int& counter) {
if (verteces[v.id].visited)
return;
++counter;
verteces[v.id].visited = true;
std::cout << v.point << "(" << counter << ") ";
for (const auto & e : graph[v]) {
traverse_graph(verteces, e.first, graph, counter);
}
}
void start_traverse_graph(std::map<int, vertex>& verteces, const vertex & v, std::map< vertex, std::map< vertex, int> >& graph) {
if (verteces[v.id].visited)
return;
verteces[v.id].visited = true;
for (const auto & e : graph[v]) {
int counter{0};
clear_visited(verteces);
verteces[v.id].visited = true;
traverse_graph(verteces, e.first, graph, counter);
}
}
bool operator<(vertex a, vertex b) { return a.point < b.point; }
int main (int argc, char *argv[]) {
vertex v1, v2;
std::map< vertex, std::map< vertex, int> > m;
std::istringstream stm {"1 2 2 3 3 1 4 1 4 5 5 3 5 6 5 7 5 8 6 4 7 6 8 9 9 10"};
std::set<vertex> vertecesSet;
std::map<int, vertex> verteces;
while (stm >> v1.point >> v2.point) {
v1.id = v1.point;
v2.id = v2.point;
m[v1];
m[v1][v2] = 1;
vertecesSet.insert({v1.point, false, v1.point});
vertecesSet.insert({v2.point, false, v2.point});
}
for(auto & el : vertecesSet)
verteces[el.id] = std::move(el); // dont need set objects anymore so move them
std::cout << "Map layout " << "\n";
std::string ss = "";
int dc = digit_count(m.rbegin()->first.point); // equals max number
for (const auto & p : m) {
std::cout << p.first.point << ss.append(" ", (dc - digit_count(p.first.point))) << "| ";
for (const auto & val : p.second)
std::cout << val.first.point << " ";
ss = "";
std::cout << "\n";
}
vertex start {5,false,5};
std::cout << "\nStart : " << start.point << "\n";
start_traverse_graph( verteces, start, m);
std::cout << "\n";
return 0;
}

pointer to an array address minus the address of an array [duplicate]

This question already has answers here:
Pointer subtraction confusion
(8 answers)
Closed 9 years ago.
I have a pointer to array, why it gives me the following output?
int main() {
int b[] = {1, 2};
cout << "size of int = " << sizeof(int) << endl;
int *pt = b;
int i = 0;
while( i++ < 2) {
cout << "pt = " << pt << ", b = " << b << endl;
cout << pt - b << endl;
(pt)++;
}
return 0;
}
code output:
size of int = 4
pt = 0x7fff576f0c2c, b = 0x7fff576f0c2c
0
pt = 0x7fff576f0c30, b = 0x7fff576f0c2c
1
pt is a pointer to the start of array b initially, why pt-b gives me the index of the array that pt points to rather than the index of the array times the size of one element.
it's because your array is really an address, and int *pt = b; essentially makes pt the exact same as b
your output is simply printing the number of times you've incremented pt since you set it to b
Remember, in the end, pointers are plain old ints, which represent an address in your logical space. Here the address b is pointing to remains constant while pt gets shifted by one.

Resources