function matlab: array initialization for more entity

253 views Asked by At

I need help about a simulink function: I have n entities, in this example only 2.

  • Attribute entity 1: ID = 1 , VALORE = 5
  • Attribute entity 2: ID = 2 , VALORE = 3

I need to call a function only one time instead of looping and if exists a y = ... don't create anymore.

function y = fcn(VALORE,ID)

y=zeros(1,2);

persistent start;

if isempty(start)  
  start=zeros(1,2);
end

if (ID==0)
  return 
end

y(ID) = start(ID);
start(ID) = start(ID) + VALORE;

enclose the values of y

y =      0     0
y =      0    36
start = 60    39
y =      0     0
y =     60     0
start = 65    39

I would, for example

y = 55 33
y = 60 33
y = 65 36

without the call y = zeros (1,2) to each function call.

1

There are 1 answers

0
Mikhail_Sam On BEST ANSWER

As far as I know, For code generation, the first appearance of a variable must establish its size. The first appearance of a variable cannot be subscripted. So you really need to use zeros.

But there is not the problem! You can get your values of y in a different ways: for example, 1. easiest way - use y like you use start - make it persistent and let it save values between function calls. 2. if you need to use y value somewhere else you can simply add third variable at entrance Y and save result to it.

I usually use third way:

function y1 = fcn(y, ID, VALORE)
y1 = zeros( 1, 2 );
y1 = y;

and now can do with it anything I want.

I am sorry if I misunderstood the question