For loop does not compile in Matlab mcode using Xilinx block

MATLABxilinxxilinx system generator

I have a simple code in xilix type mblock in simulink:

function q = test1( n)
q = 0;

  for i = 1:n
    q = i;
  end;

end

If I run this code naively in matlab console, it works fine. However, when I want to simulate the xilinx block in simulin, it shows the following error:

enter image description here

Does that mean that I cannot have any dynamic loops in there?

Best Answer

While I have never used Matlab with Simulink, as the intent is to translate the (debugged) design into hardware implementation on FPGA, this is closely related to the problem of what is synthesisable in VHDL, and what is not.

In the finished hardware design, and in synthesisable VHDL code, you can of course NOT have dynamic loops; that would imply a dynamically varying number of gates and registers on your chip!

This is not a real dilemma, however : you transform the dynamic loop into a static loop whose size is the upper bound of the dynamic variable, and make execution of the loop body conditional on the actual dynamic value.

So in VHDL, given the following declarations:

subtype n_type is natural range 1 to 20; 
variable n : n_type;

(or any other way of establishing the valid range of n) you would transform your dynamic loop

  for i in 1 to n loop
    q := i;
  end loop;

into a static, bounded one

  for i in n_type'range loop
    if i <= n then
       q := i;
    end if;
  end loop;

Then the loop bounds are known at compile time and the code is synthesisable.

This is such a simple transformation (at least, in any language that has a basic notion of ranged integer types and attributes) that I would be disappointed that Matlab/Simulink can't do it, but that seems to be what your compiler messages are saying.

However it is so easy to do by hand (unless there is no way to place an upper bound on n) that it really isn't an obstacle.