error with nested loops when using matlab coder, however there are NO nesting at all

775 Views Asked by At

I try to to use matlab coder to a function with many arrays:

function [y, fv, a_1_1, a_2_1, ..., a_3_1, ...] = test_ff( x, ffW, ffb, kernel_2_1_1, b_2_1, ..., kernel_4_6_12, b_4_12) %#codegen
 a_1_1 = x;
 a_2_1 = zeros(24, 24, size(x, 3));
 a_2_1 = a_2_1 + convn(a_1_1, kernel_2_1_1, 'valid');
 a_2_1 = 2 ./ (1 + exp(- 2 * (b_2_1 + a_2_1))) - 1;
     ...
 c_5_12 = convn(a_4_12, ones(2, 2) / ( 2 * 2), 'valid');
 a_5_12 = c_5_12(1 : 2 : end, 1 : 2 : end, :);
 sa = size(a_5_1);
 fv = zeros( sa(1) * sa(2) * 12, sa(3));
 block_size = sa(1) * sa(2);
 fv(0 * block_size + 1 : 1 * block_size, :) = reshape(a_5_1, sa(1) * sa(2), sa(3));
 ...
 y = 1 ./ (1 + exp( - ( ffW * fv + repmat(ffb, 1, size(fv, 2)))));

end

It's just multiplication and convolution of big number of matrices. When I try to generate C++ code with the commands:

cfg = coder.config('mex');
cfg.TargetLang = 'C++';
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';
codegen -config cfg -v  -report test_function -args {coder.typeof(0, [28, 28, Inf], [0, 0, 1]), ...}

I get the following error:

 fatal error C1061: compiler limit : blocks nested too deeply

It's a known bug of the compiler and it is connected with the number of namespaces. The description of the bug and a workaround can be found here

http://support.microsoft.com/kb/315481/en-us

So, I deduced that I have the same problem since matrix multiplication results in a loop in the generated C++ code, so I have too many loops and this leads to the error. I want to use the workaround described in the link above and ebmrace each matrix multiplication or convolution with '{' and '}'. However, I do not know how to do that. I tried to use command

coder.cinclude('file_with_brace.h')

but it inserts '{' in the beginning of the source file instead of the place where I wanted the '{' to be. Can smb give me advice what can I do in this situation? Thanks!

1

There are 1 best solutions below

2
On

To insert {, you tried coder.cinclude('file_with_brace.h') but you should type

if one>0

and similarily to insert }, you should use

end

to insert } in the C code. And replace

function [y, fv, a_1_1, a_2_1, ..., a_3_1, ...] = test_ff( x, ffW, ffb, kernel_2_1_1, b_2_1, ..., kernel_4_6_12, b_4_12)

by

function [y, fv, a_1_1, a_2_1, ..., a_3_1, ...] = test_ff( one, x, ffW, ffb, kernel_2_1_1, b_2_1, ..., kernel_4_6_12, b_4_12)

And when you call test_ff, replace test_ff( by test_ff(1,.

Note: this inserts a for loop, so use it once for each pack of 10 for loop.

Then read p5-4 of http://www.mathworks.com/help/pdf_doc/coder/coder_ug.pdf that states you should initialize any variable before the if if it is needed after the end.