IAGO SESTREM Ochoa IAGO SESTREM Ochoa - 5 months ago 25
C Question

matlab for (decreasing) in C

How can I convert a matlab for to C language?


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

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

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

Is my conversion correct?


Is my conversion correct?

No, see below.

for loops always have a form like


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--)