0

I want to model a for loop system in Simulink, how I can model the following MATLAB syntax into Simulink model?

N=3;
    for    i=0:1:N
    sum(i+1)=factorial(i)/factorial(N);  
    end

I have tried for loop sub systems in Simulink and also Sum block for iteration loop but doesn't help me. factorial function can be calculated with FCN function. Suggest me the ways to resolve this model with step time.

  • I suggest you change (in Matlab) `factorial(i)/facrorial(N)` to `1/prod(i+1:N)`. That will save computations an avoid overflow (if `N` is large). Also, it's best [not to use `i` as a variable name](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) – Luis Mendo Mar 17 '14 at 11:10
  • OK, it seems very efficient way, how can I save the computations if I have, factorial(N)/(factorial(i)*factorial(N-i)) ? Also, how can i avoid imaginary unit that gives efficiency? –  Mar 17 '14 at 11:20
  • Replace `for i=` by `for ii=`; and replace `factorial(N)/(factorial(i)*factorial(N-i))` by `prod((N-ii+1:N)./[1:ii])` – Luis Mendo Mar 17 '14 at 11:35
  • sum(ii+1) remains there? does it affects the performance? –  Mar 17 '14 at 11:42
  • @LuisMendo it gives following error: Computed maximum size of the output of function 'colon' is not bounded. Static memory allocation requires all sizes to be bounded. The computed size is [1 x :?]. –  Mar 17 '14 at 11:51
  • 1
    This can be done quite easily using a MATLAB function block, but since the number of elements in the output is dependent on the value of N (which I assume is not really hard coded a 3, but rather can change during a simulation) you'll need to use variable sized signals. Search the doc for that term to learn how to define them. – Phil Goddard Mar 18 '14 at 14:28

1 Answers1

0

If you have the code already in matlab use a embedded matlab function to implement it i your simulink model. This is in general quite efficient since it will be compiled (compared to interpreted matlab function blocks)

renzop
  • 1,194
  • 2
  • 12
  • 26