# Code generation for sum function in MATLAB

In cross correlation we use the below command to calculate the sum after elementary multiplication of the vectors. But when we try to convert this Matlab code to vhdl using HDL coder, this command is not defined by HDL coder. Is it possible to write code for below line without using 'sum' builtin function please.

xc(i)=sum((y1(j1:k1)).*y2(j2:k2));


where j1, j2, k1 and k2 are the starting and ending limits. y1 and y2 are two vectors and are being multiplied element wise and the result is being added.

Thanks

• Well, yeah... Using for loop would we the easiest way... – jojek Jan 12 '16 at 9:42
• @jojek, Thanks for the reply.Can you please elaborate little bit further.I will really appreciate it! – Haider Jan 12 '16 at 9:44
• sum becomes a loop that sums all the elements to the accumulator. Anyway I don't understand why are you trying to do that since sum is supported by HDL Coder – jojek Jan 12 '16 at 9:55
• @jojek Thanks for the link. Even if sum is supported by hdl coder,still I am getting error : MATLAB for code generation only supports SumModes 'SpecifyPrecision' and 'KeepLSB' for 'SUM' when the size of the inputs can vary at run-time. Can you please comment on it.Why this error? – Haider Jan 12 '16 at 11:24
• You have to specify how to calculate the sum will be calculated for Fixed-Point object. Take a look at fimath specification of SumMode and choose the position of your radix point, or simply use the KeepLSB - I suggest it. All of that is due to the way Fixed Point math is being done and how you have to "juggle" with both precision and overflows. For variable input size it is obviously difficult to determine how much dynamic range you need. Also please have a look on the example for product and sum. All of that should get you started. – jojek Jan 12 '16 at 11:52

Because the size of y1(j1:k1) and y2(j2:k2) must be the same then: $$k_1-j_1 = k_2-j_2$$ and you will also have something like: $j_1+N=j_2$ then you could write a for loop like this:
xc(i) = 0