IAGO SESTREM Ochoa IAGO SESTREM Ochoa - 3 months ago 8
C Question

matlab for(decreascing) in C

How can I convert a matlab for to C language?

Matlab:

for i = 1:l,
for a = d:-1:2,
mem(a) = mem(a-1);
end;
mem(1) = s(i);
y(i) = a0*mem(1) + a1*mem(d0) + a2*mem(d);
end;


C (that's what I did, but it seems not working):

for (i = 0; i < l; i++) {
for (j=d; j==2; j--) {
mem[j]=mem[j-1];
}
mem[0]=x[i];
y[i]= a0*mem[0]+a1*mem[d0]+ a2*mem[d];
}


Is my conversion correct?

Answer

Is my conversion correct?

No, see below.

for loops always have a form like

for (FROM; WHILE; NEXT) BODY

and are executed like:

  1. evaluate the FROM expression (usually initialization)
  2. evaluate the WHEN expression
    • if it is true, goto 3
    • else, exit the loop
  3. then evaluate the BODY
  4. evaluate NEXT (usually advancing the iteration)
  5. goto 2

Note that the conditional is always a while, and never an until. They're logically opposites.

Now, look at your two loops:

for (i = 0; i < l; i++) {

runs while i < 1. As soon as that condition is false, the loop exits.

for (j=d; j==2; j--)

You want this to loop until j==2, but that's not how for loops work. It actually loops while j==2, which is to say, never. It should be

for (j=d; j >= 2; j--)
Comments