Does Simulink and Matlab has different compiler for user defined functions?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Zeljko Tomicevic
el 3 de En. de 2018
Comentada: Birdman
el 12 de En. de 2018
I wrote a function in Matlab and it works just fine. When I put it in the Simulink User defined block Matlab fcn it does not work. Simulin returns error on array mismatch.
function G = my_fcn(X)
nule = zerocros(X);
k = size(nule);
n = 1;
i = 0;
G = [];
for i=1:k(1,1)
if i + 10 > k(1,1)
break
end
Y = nule(i:i+10);
if Y(11) > 10
G(:,n) = Y - Y(1);
G(:,n) = G(:,n)./G(11,n);
G(1,n) = nule(i);
G(11,n) = Y(11);
n = n + 1;
end
end
Simulink returns:
Index exceeds matrix dimensions. The array G is empty and therefore has no valid indices. Error in 'za_simulink_zerocross/MATLAB Function' (line 13) G(:,n) = Y - Y(1);
("Y" is one dimensional array and its size is always 11.)
Matlab returns nothing and function works. 1. What is the difference in Matlab vs Simulink fcn? 2. How to define some kind of flexible array that can increment number of columns.
Best
0 comentarios
Respuesta aceptada
Birdman
el 3 de En. de 2018
This is the main property of Simulink. If you write a function yourself, you need to define the size of output at the very beginning of the function. The error comes from that you define G empty, in which Simulink will think that its size is fixed and won't change during the simulation. Therefore, you need to preallocate some space for your output G. Consider the following approach:
function G = my_fcn(X)
G = zeros(11,1);
nule = zerocros(X);
k = size(nule);
n = 1;
i = 0;
for i=1:k(1,1)
if i + 10 > k(1,1)
break
end
Y = nule(i:i+10);
if Y(11) > 10
G(:,n) = Y - Y(1);
G(:,n) = G(:,n)./G(11,n);
G(1,n) = nule(i);
G(11,n) = Y(11);
n = n + 1;
end
end
At the very beginning, I told Simulink that output G is going to be a column vector which has 11 rows. If you try to create new row during the simulation, it will throw an error, therefore always be careful to stay within predefined sizes.
14 comentarios
Birdman
el 4 de En. de 2018
Editada: Birdman
el 4 de En. de 2018
How about I give you only the numerical values and you choose which ones to use in your calculation? You can create your own 11 column array by some manipulations. Use the following code after you run the simulation in command line:
a=simout.signals.values;
a=unique(a(isnumeric(a) & ~isnan(a) & a~=0)).'
Más respuestas (1)
Zeljko Tomicevic
el 12 de En. de 2018
1 comentario
Birdman
el 12 de En. de 2018
It depends on how you look at things. On the other hand, Simulink offers so much different toolboxes ready to be used. On MATLAB, you need to write the code to say the least. But anyway, do your thing how you find easy.
Ver también
Categorías
Más información sobre Simulink Functions en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!