Eigen: Replicate (broadcast) by rows - optimization

I'd like to replicate each row of a matrix M without any copy occurring (i.e. by creating a view):
0 1 0 1
2 3 -> 0 1
2 3
2 3
M.rowwise().replicate(n) is a shorcut for M.replicate(1,n) which seems kind of useless.
The following snippet does a copy, and cannot work if M is an expression.
Eigen::Index rowFactor = 2;
Eigen::MatrixXi M2 = Eigen::Map(M.data(), 1, M.size()).replicate(rowFactor, 1);
M2.resize(M.rows()*rowFactor, M.cols()) ;
In some situation, I may use the intermediate view Eigen::Map<Eigen::MatrixXi>(M.data(), 1, M.size()).replicate(rowFactor, 1) by reshaping the other operands, but that's not very satisfying.
Is there a proper way to achieve this broadcast view?

What you want is essentially a Kronecker product with a matrix of ones. You can use the (unsupported) KroneckerProduct module for that:
#include <iostream>
#include <unsupported/Eigen/KroneckerProduct>
int main() {
Eigen::Matrix2i M; M << 0, 1, 2, 3;
std::cout << Eigen::kroneckerProduct(M, Eigen::Vector2i::Ones()) << '\n';
}
Being 'unsupported' means that the API of the module is not guaranteed to be stable (though this module has not changed since its introduction, I think).

Related

What does typedef enum syntax like '1 << 0' mean? [duplicate]

This question already has answers here:
What are bitwise shift (bit-shift) operators and how do they work?
(10 answers)
Closed 9 years ago.
I'm somewhat familiar with the typedef enum syntax of C and C++. I'm now programming in Objective-C and came across the syntax in the following example. I'm not sure if the syntax is Objective-C specific or not. But, my question is in the following code snippet, what does syntax like 1 << 0 mean?
typedef enum {
CMAttitudeReferenceFrameXArbitraryZVertical = 1 << 0,
CMAttitudeReferenceFrameXArbitraryCorrectedZVertical = 1 << 1,
CMAttitudeReferenceFrameXMagneticNorthZVertical = 1 << 2,
CMAttitudeReferenceFrameXTrueNorthZVertical = 1 << 3
} CMAttitudeReferenceFrame;
This is common to the C-family of languages, and works identically in C, C++, and Objective-C. Unlike Java, Pascal, and similar languages, a C enum is not limited to the values named for it; it actually is an integral type of a size that can represent all the named values, and one can set a variable of the enum type to an arithmetic expression in the enum members. Typically, one uses bit shifts to make the values powers of 2, and one uses bit-wise logical operations to combine values.
typedef enum {
read = 1 << 2, // 4
write = 1 << 1, // 2
execute = 1 << 0 // 1
} permission; // A miniature version of UNIX file-permission masks
Again, the bit-shift operations are all from C.
You can now write:
permission all = read | write | execute;
You could even include that line in the permission declaration itself:
typedef enum {
read = 1 << 2, // 4
write = 1 << 1, // 2
execute = 1 << 0, // 1
all = read | write | execute // 7
} permission; // Version 2
How do you turn execute on for a file?
filePermission |= execute;
Note that this is dangerous:
filePermission += execute;
This will change something with value all to 8, which makes no sense.
<< is called the left shift operator.
http://www.techotopia.com/index.php/Objective-C_Operators_and_Expressions#Bitwise_Left_Shift
Long story short 1 << 0 = 1, 1 << 1 = 2, 1 << 2 = 4 and 1 << 3 = 8.
It looks like the typedef is representing a bit field value. 1 << n is 1 shifted left n bits. So each enum item represents a different bit setting. That particular bit set or clear would indicate something being one of two states. 1 shifted left by zero bits is 1.
If a datum is declared:
CMAttitudeReferenceFrame foo;
Then you can check any one of four independent states using the enum values, and foo is no bigger than an int. For example:
if ( foo & CMAttitudeReferenceFrameXArbitraryCorrectedZVertical ) {
// Do something here if this state is set
}

<< in UITableView Enum

A << operator is used in UITableViewCell, as listed below:
enum {
UITableViewCellStateDefaultMask = 0,
UITableViewCellStateShowingEditControlMask = 1 << 0,
UITableViewCellStateShowingDeleteConfirmationMask = 1 << 1
};
I had been to this post << operator in objective c enum? but still not clear about the use of << operator.
The same above mentioned Enum and be written as mentioned below, then why is it so, they have used << operator?
enum {
UITableViewCellStateDefaultMask = 0,
UITableViewCellStateShowingEditControlMask = 1,
UITableViewCellStateShowingDeleteConfirmationMask = 2
};
The post you have linked explains why quite clearly. The << operator in C shifts numbers left by the specified number of bits. By shifting a 1 into each column, it is easy to see that the enum options can be bitwise ORed together. This allows the enum options to be combined together using the | operator and held in a single integer. This would not work if the enum declaration was as follows:
enum {
UITableViewCellStateDefaultMask = 0, (= 00 in binary)
UITableViewCellStateShowingEditControlMask = 1, (= 01 in binary)
UITableViewCellStateShowingDeleteConfirmationMask = 2, (= 10 in binary)
UITableViewCellStateThatIJustMadeUpForThisExample = 3 (= 11 in binary)
};
As 3 = 11 in binary, it is not possible to know from a single integer if you have the state UITableViewCellStateThatIJustMadeUpForThisExample or UITableViewCellStateShowingEditControlMask ORed with UITableViewCellStateShowingDeleteConfirmationMask.
The enum values give names to bits that are to be used in a bitmask. The bits in a bitmask by value are 1, 2, 4, 8, 16, ... (the powers of two). These values can be more clearly shown using the expressions (1<<0, 1<<1, 1<<2, 1<<3) -- i.e,. 1 shifted to the left by 0, 1, ... places. It's clearly and less error prone than listing the powers of 2 as decimal constants.
When you use the values, they are normally combined using a bitwise-OR operation ('|'). The goal is to specify zero or more bits, each of which has a specific meaning. Using a bitmask allows you to specify them independently but compactly. You may wish to read more on bitmasks for more details and examples.

enum default values understanding

i am using objective-c to develop ios applications
i found in the documentations that enum have default values like this : "1<<0"
i don't understand this default value
example:
enum {
UIDataDetectorTypePhoneNumber = 1 << 0,
UIDataDetectorTypeLink = 1 << 1,
UIDataDetectorTypeAddress = 1 << 2,
UIDataDetectorTypeCalendarEvent = 1 << 3,
UIDataDetectorTypeNone = 0,
UIDataDetectorTypeAll = NSUIntegerMax
};
so, what is the default value for each element in this enum ?
thanks
That is an enum with bitwise values or bit flags. Each value is an binary value in which only one bit is set to 1 and all the others are set to 0. That way you can store in a value as much flags as bits of an integer number has.
The shift left operator '<<' is a displacement of bits to the left or to the most significant side of the binary number. It is the same that calculating a "* 2" (times two) operation.
For example in the enum you have send in your question, the first value, UIDataDetectorTypePhoneNumber, is 1. The second one, UIDataDetectorTypeLink, is 2 and the third one, UIDataDetectorTypeAddress, is 4.
You combine that values as flags to set some different bits in the same integer:
NSInteger fooIntValue = UIDataDetectorTypePhoneNumber | UIDataDetectorTypeLink;
As '|' operation is bitwise, the result will be a binary value ...0011, that is 3. And you are indicating that your variable fooIntValue has two flags set to true for two different properties.
This << sign is for shifting bits to the left (multiplying by 2).
1 << 0 equals 1 (0b00000001)
1 << 1 equals 2 (0b00000010)
1 << 2 equals 4 (0b00000100)
Usually, if you dont asign any values, compiler will define first value as 0, second as 1 and so on. You can alway assign values yourself if you prefer (assignment that you're refering to is usually used for bitmasks, where each bit in a byte or a word has it's own meaning).

<< operator in objective c enum?

I was looking for something and got in to this enum is apple UITableViewCell.h.
I am sorry if this is trivial but I wonder/curious what is the point of this.
I know the << from ruby but I don't really understand this enum ?
enum {
UITableViewCellStateDefaultMask = 0,
UITableViewCellStateShowingEditControlMask = 1 << 0,
UITableViewCellStateShowingDeleteConfirmationMask = 1 << 1
};
Thanks
BTW
Found it as a great way to learn coding, I am trying once in a day to get into the header files of at list on object.
Shani
These are bit-field flags. They are used because you can combine them using the bitwise-OR operator. So for example you can combine them like
(UITableViewCellStateShowingEditControlMask | UITableViewCellStateShowingDeleteConfirmationMask)
They work by having one bit set in an integer. In this example, in binary,
UITableViewCellStateShowingEditControlMask = 0000 0001
UITableViewCellStateShowingDeleteConfirmationMask = 0000 0010
When they are OR'ed together, they produce 0000 0011. The framework then knows that both of these flags are set.
The << operator is a left-shift. It shifts the binary representation. So 1 << 1 means
0000 0001 shifted left by one bit = 0000 0010
1 << 2 would equal 0000 0100.
Its actually BItwise shift operator
<< Indicates the bits are to be shifted to the left.
>> Indicates the bits are to be shifted to the right.
So in your statement the value of 1 << 0 is 1 and 1 << 1 is 2
It's a common trick in C to use the bitwise shift operator in enum values to allow you to combine enumeration values with the bitwise or operator.
That piece of code is equivalent to
enum {
UITableViewCellStateDefaultMask = 0,
UITableViewCellStateShowingEditControlMask = 1, // 01 in binary
UITableViewCellStateShowingDeleteConfirmationMask = 2 // 10 in binary
};
This allows you to bitwise or two or more enumeration constants together
(UITableViewCellStateShowingEditControlMask | UITableViewCellStateShowingDeleteConfirmationMask) // == 3 (or 11 in binary)
to give a new constant that means both of those things at once. In this case, the cell is showing both an editing control and a delete confirmation control, or something like that.
These operand called bitshift. Bitshift operand can be preferred for
2 reasons.
- For fast operation
- Use multiple bool value in one time.
For example : 1<<2 is a left shift; that means
1 : 0001,
2 : 0010
1 << 2 this line means is 2 should be left one bit. As a result 0010 shifted to 0100
Also shifted value must ordered as a 1,2,4,8,16...
typedef NS_OPTIONS(int, EntityEngineer) {
EntityEngineeriOS = 1 << 0,
EntityCategoryAndroid = 1 << 1,
EntityCategoryDB = 1 << 2,
EntityCategoryTeamLead = 1 << 16,};
Now, we want to check mutiple boolean in below line,
char engineer = (EntityEngineeriOS | EntityCategoryAndroid);
char 0011 = (0001 | 0010);
if (engineer & EntityEngineeriOS) {
NSLog(#"we are looking for a developer who can write objective c or java");
}
if (engineer & EntityCategoryDB) {
NSLog(#"we are not looking for a DB manager");
}
Result : we are looking for a developer who can write objective c or java
That is the bitshift operator. That is used commonly for objects that may have multiple behaviors (each enum being a behavior).
Here is a similar post that may clarify it better.
These types of operator are called bitwise operator which operates on bit value of a number. These operation are very fast as compared to other arithematic operations.

the buffer and output sequence of cout and printf

I know cout and printf have buffer today, and it is said that the buffer is some like a stack and get the output of cout and printf from right to left, then put them out(to the console or file)from top to bottem. Like this,
a = 1; b = 2; c = 3;
cout<<a<<b<<c<<endl;
buffer:|3|2|1|<- (take “<-” as a poniter)
output:|3|2|<- (output 1)
|3|<- (output 2)
|<- (output 3)
Then I write a code below,
#include <iostream>
using namespace std;
int c = 6;
int f()
{
c+=1;
return c;
}
int main()
{
int i = 0;
cout <<"i="<<i<<" i++="<<i++<<" i--="<<i--<<endl;
i = 0;
printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- );
cout<<f()<<" "<<f()<<" "<<f()<<endl;
c = 6;
printf("%d %d %d\n" , f() , f() ,f() );
system("pause");
return 0;
}
Under VS2005, the output is
i=0 i++=-1 i--=0
i=0 i++=-1 i--=0
9 8 7
9 8 7
Under g++( (GCC) 3.4.2 (mingw-special)), the output is,
i=0 i++=0 i--=1
i=0 i++=-1 i--=0
9 8 7
9 8 7
It seems that the buffer is like a stack. However, I read C++ Primer Plus today, and it is said that the cout work from left to right, every time return an object(cout), so "That’s the feature that lets you concatenate output by using insertion". But the from left to right way can not explain cout< output 9 8 7
Now I'm confused about how cout's buffer work, can somebody help me?
The output of:
printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- );
is unspecified. This is a common pitfall of C++: argument evaluation order is unspecified.
Not so with the cout case: it uses chained calls (sequence points), not arguments to a single function, so evaluation order is well defined from left to right.
Edit: David Thornley points out that the behavior of the above code is in fact undefined.
This is not a bug, nor is it anything to do with output buffering.
The order of execution of the i-- and i++ operations is not defined when they're invoked more than once as parameters to the same function call.
To elaborate (and possibly correct) Iraimbilanja's mention of "sequence points", the cout version is equivalent to:
(((cout << a) << b) << c)
Effectively, it's actually three separate function calls, each of whose parameters are evaluated in order, even though it's written like a single statement.
The << operator is really ostream& operator<<(ostream& os, int), so another way of writing this is:
operator<< ( operator<< ( operator<< ( cout, a ), b ), c )
Since for the outer call it's not (AFAIK) defined which order the two parameters are evaluated, it's perfectly possible for the right-hand "c" parameter (or in your case "i--") to happen before the left hand parameter is evaluated.
if possible try updating to gcc >= 4. i just ran this on 4.0.1 and it executes just dandy.