Message Boards Message Boards

GROUPS:

Perform element-wise matrix operations (EqualTo)?

Posted 5 years ago
3959 Views
|
4 Replies
|
0 Total Likes
|

Hi,

I am stuck on a problem that most likely has an easy solution..

I have 2 symbolic matrices:

amat = {{a11, a12}, {a21, a22}, {a31, a32}, {a41, a42}};
bmat = {{b11, b12}, {b21, b22}, {b31, b32}, {b41, b42}};

I want to end up with this output:

{a11 == b11, a12 == b12, a21 == b21, a22 == b22, a31 == b31, 
 a32 == b32, a41 == b41, a42 == b42}

I get this when I directly thread: Thread[amat == bmat]

{{a11, a12} == {b11, b12}, {a21, a22} == {b21, b22}, {a31, 
   a32} == {b31, b32}, {a41, a42} == {b41, b42}}

I can get the output I want if I flatten to lists prior to threading: Thread[amat//Flatten = bmat//Flatten] but I am hoping someone can show me a more elegant way (from the documentation it seems like Thread[amat == bmat, 2] should work but it doesn't.

Thank you for any suggestions. Rebecca

4 Replies
In[1]:= Thread[Flatten[amat] == Flatten[bmat]]

Out[1]= {a11 == b11, a12 == b12, a21 == b21, a22 == b22, a31 == b31, 
 a32 == b32, a41 == b41, a42 == b42}
In[4]:= Flatten[Thread /@ Thread[amat == bmat]]

Out[4]= {a11 == b11, a12 == b12, a21 == b21, a22 == b22, a31 == b31, 
 a32 == b32, a41 == b41, a42 == b42}

More elegant would be to use MapThread if you want to do 'deeper' threading, Thread does not have a a level-specification.

amat = {{a11, a12}, {a21, a22}, {a31, a32}, {a41, a42}}; 
bmat = {{b11, b12}, {b21, b22}, {b31, b32}, {b41, b42}};
MapThread[Equal, {amat, bmat}, 2]
Join @@ %

Join @@ can also be replaced by Catenate@ or Flatten@, whatever you like...

Posted 5 years ago

You already have a direct and simple solution( flatten first) using basic Mathematica and it works for any depth of nesting. A different way to do that is to use a Listable function (alias for "==") and flatten the result.

eq[x_, y_] = Equal[x, y]; SetAttributes[eq, Listable];
Flatten[eq[amat, bmat]]

{a11 == b11, a12 == b12, a21 == b21, a22 == b22, a31 == b31, 
 a32 == b32, a41 == b41, a42 == b42}
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract