HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Computing six dot products involving one common input vector

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sixinvolvingdotinputonecommoncomputingvectorproducts

Problem

I have created a Matlab Simulink model with a series of dot products.

Embedded Coder generates a for loop for each dot product, as evidenced by this excerpt of the generated output:

/* DotProduct: '/Dot Product1' incorporates:
 *  Inport: '/LngPwr'
 */
EPAR_SPAF_dot_B.DotProduct1 = 0.0F;
for (temp_ = 0; temp_ /Dot Product1' */

/* DotProduct: '/Dot Product2' incorporates:
 *  Inport: '/ShrtPwr'
 */
EPAR_SPAF_dot_B.DotProduct2 = 0.0F;
for (temp_ = 0; temp_ /Dot Product2' */


Can I improve the Simulink model such that it will compile to better code?

I want to avoid using embedded matlab or a S-function for the purposes of maintainability.

Solution

There is a common mathematical operation involving many dot products: it's called matrix multiplication.

$$ \left[\begin{matrix}v_1 & v_2 & v_3 & v_4\end{matrix}\right]
\left[\begin{matrix}
a_1 & b_1 & c_1 \\
a_2 & b_2 & c_2 \\
a_3 & b_3 & c_3 \\
a_4 & b_4 & c_4
\end{matrix}\right] =
\left[\begin{matrix}(\vec{v}\cdot\vec{a}) & (\vec{v}\cdot\vec{b}) & (\vec{v}\cdot\vec{c})\end{matrix}\right]
$$

So, I recommend that you concatenate vectors \$\color{lightgreen}1\$ to \$\color{lightgreen}6\$ into a matrix and perform matrix multiplication.

You can also transpose and swap the matrices:

$$
\left[\begin{matrix}
a_1 & a_2 & a_3 & a_4 \\
b_1 & b_2 & b_3 & b_4 \\
c_1 & c_2 & c_3 & c_4 \\
\end{matrix}\right]
\left[\begin{matrix}v_1 \\ v_2 \\ v_3 \\ v_4\end{matrix}\right]
=
\left[\begin{matrix}\vec{a}\cdot\vec{v} \\ \vec{b}\cdot\vec{v} \\ \vec{c}\cdot\vec{v}\end{matrix}\right]
$$

Context

StackExchange Code Review Q#127626, answer score: 5

Revisions (0)

No revisions yet.