DEV Community

dinhanhx
dinhanhx

Posted on

How stupid is Matlab for loop?

Before I answer the question in the title, let look at how for loop in Python and C are expressed in human language

Python

v = [1, 2, 3, 4]
for i in v:
    print(i)
Enter fullscreen mode Exit fullscreen mode

Human language: there is a variable v assigned a list [1, 2, 3, 4]. Then for each element in v (stored in variable i) is printed.

You can see it's very straight forward.

C

int v[] = {1, 2, 3, 4};
int i = 0;
for(i = 0; i < 4; i++) {
    print("%d", v[i]);
}
//for ( init; condition; increment ) {
//   statement(s);
//}
Enter fullscreen mode Exit fullscreen mode

Human language: there is a variable v assigned an array {1, 2, 3, 4}. Then, a variable i stores integer 0. Then for i starts with 0 (the initial), when is smaller than 4 (the condition), increase i by one (the increment) and print the value element of v by the index (the statment).

It's longer than Python (of course, C is a low level language). However, the description is still straightforward. It's just added some linking words to ease human mind.

Matlab

for v = [1 2 3 4]
   disp(v);
end
Enter fullscreen mode Exit fullscreen mode

By instinct, when you see v = [1 2 3 4], you will say a variable v assigned an array [1 2 3 4]. Guess what? it becomes the iterator when being added to a for loop.

I tried to express this thing in human language that is close to the code but nothing works.

Try 1: for v is assigned to an array, display element of v

Here you can see it doesn't show that v is an iterator. And v has two meanings.

Try 2: for each v in [1 2 3 4], display v

But v is assigned to an array?? We all know equal sign and belong sign are two different things.

There isn't a proper human language description for this one. And you have to remember that = has two meanings:

  • assign when not in a for loop
  • in when in a for loop

If MathWork read this blog, please use something different than =. You can use in or belongto or iterate.

Now you see how stupid it is.

Top comments (4)

Collapse
 
xuanvunguyen profile image
Xuan Vu Nguyen

So if "=" is equal "belong to", then how to do assignment in MatLab?

Collapse
 
dinhanhx profile image
dinhanhx

You also use = for that.

Collapse
 
xuanvunguyen profile image
Xuan Vu Nguyen

wow what a profound and creative way to use =, absolutely not confusing, counter-intuitive and mistake-prone though, prob to MatLab

Thread Thread
 
dinhanhx profile image
dinhanhx

Stay tune for more Matlab profound "feature"