MATLAB: Whats wrong with that loop

MATLABsimulink

Hi,
I wrote loop in matlab function (here is part of it):
for k=1:ADDR
if(I>0)
[~,I] = min(temp);
if(reg(I) == 1)
temp(I) = +inf;
reg(I) = 0;
else
reg(I) = 1;
temp(I) = +inf;
end
else
[~,I] = max(temp);
reg(I) = 1;
temp(I) = -inf;
end
end
reg is 20 bit array and it is output from the function. the input to the function are: ADDR runs from 0 to 20, temp is input array of 20 values and changing all time. the function search the minimum value of temp and write the index of it into reg, for example:
if(I>0) and temp = [21 24 25 2 35 8 14 27 78 85 54 29 96 35 1 74 36 35 28 41] temp values can change all the time – next ADDR it is a differnt values. if bit is set to 1, it should be last till ADDR reached 20. for the first one, the loop searh the minimum values from 20 input values. set the bet reg to 1 and in the next ADDR(ADDR=2) the loop will search the next minimum from 19 inputs values and setanother bit ti one in reg. and so on/
for example: if ADDR=0 if(I>0) and temp = [21 24 25 2 35 8 14 27 78 85 54 29 96 35 1 74 36 35 28 41] result shuld be: reg = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] if ADDR=1 if(I>0) and temp = [21 24 25 2 35 8 14 27 78 85 54 29 96 35 1 74 36 35 28 41] the minimum of that array is 1 and its location is index=15 (counting from left..) result shuld be: reg = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0]
for ADDR=2 if(I>0) and temp = [38 25 25 45 35 18 14 27 78 85 54 29 96 35 45 74 36 35 28 41] the minimum of that array is 14 and its location is index=7 (counting from left..) result shuld be: reg = [0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0]
ADDR=3 if(I>0) and temp = [638 245 12 45 35 18 74 27 88 85 54 29 916 35 465 74 36 325 28 441] the minimum of that array is 12 and its location is index=3 (counting from left..) result shuld be: reg = [0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0]
and so on till ADDR=20:
result shuld be:
reg = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
the problem her is that loop does not luck those reg bits – the location(indexing) changing all the time. It's adding 1 bits into reg, as far as ADDR increment, but the locations of the inexing changing all time.
Someone can help me to solve it ?
Thanks, Henry.

Best Answer

I have not understood your explanation, but one very obvious problem with your loop, is that nothing in it depends on k. Hence, it will do exactly the same thing each iteration.
Also, why the Simulink tag?