Can I custum "for" loop for my class instance?

3 ビュー (過去 30 日間)
Qixiang Zou
Qixiang Zou 2017 年 8 月 4 日
コメント済み: Qixiang Zou 2017 年 8 月 11 日
Suppose I defined a class "MyClass", how can I implement an iterator for it? For example, if I write MyClass similiar to containers.Map, how can I implement my class so that following code is legal?
``` matlab
for [key, val] = myClassObj
do something;
end
```
In c++, if methods "begin", "end" have been defined, then I can write something like this
``` cpp
for (auto & element : obj) {
dosomething();
}
```
Similarly, for python, defining "__iter__" and "next/__next__" makes following code possible
``` python
for element in obj:
dosomething()
```
Is there a way to do so for "MyClass" in matlab? Matlab's "for" loop is just a range-based loop, so I think matlab should allow me to use similar syntax for "MyClass".
  2 件のコメント
Adam
Adam 2017 年 8 月 4 日
編集済み: Adam 2017 年 8 月 4 日
Code that tries to declare two variables on the line of a for statement is not going to be valid syntax under any circumstance, whether using a class or any other function that does this.
e.g.
for [a, b] = max( rand(7) )
gives a syntax error.
If you give more information on what you are trying to do rather than trying to enforce a syntax that simply doesn't work then we can provide more help, but trying to crowbar in desired syntax just isn't going to work.
Qixiang Zou
Qixiang Zou 2017 年 8 月 11 日
just return key is also ok,..
for key = myObj
do something;
end
I just want to know, how to overload the for loop for my class.

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2017 年 8 月 4 日
編集済み: Jan 2017 年 8 月 4 日
No, this is not valid Matlab syntax:
for [key, val] = myClassObj
do something;
end
The for command is defined for vector only, but accepts arrays also. The argument is evaluated when the for command is reached the first time. You code would look like this:
keySet = keys(myClassObj);
for k = 1:myClassObj.Count
key = keySet{k};
value = values(myClassObj, key);
do something;
end

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!