How to increment a variable
1,159 ビュー (過去 30 日間)
古いコメントを表示
Hello. I couldn't find a way to increment a variable in MATLAB using the ++ operator. Can you help me, please? Is there a function or an operator that I can use?
Thanks in advance.
採用された回答
John D'Errico
2016 年 8 月 26 日
編集済み: MathWorks Support Team
2019 年 5 月 22 日
To increment a variable X, simply use
X = X+1;
MATLAB does not support the increment operator ++.
12 件のコメント
John D'Errico
2022 年 9 月 14 日
@Jhonler you can try, but since it is not legal MATLAB syntax, it won't work. If all languages used exactly the same syntax and code, then we would only use one language.
その他の回答 (2 件)
Wayne King
2013 年 12 月 24 日
編集済み: Walter Roberson
2022 年 1 月 21 日
How about just
a = a+1;
a = 1;
x = zeros(10,1);
for k = 1:10;
x(a)= k^2;
a = a+1;
end
Of course, you would never write a loop for the above, or write the loop like that even if you did, but hopefully you get the point.
2 件のコメント
Nivethana Narayanan
2021 年 11 月 28 日
a = a+1 doesnt work as MATLAB complains that a is Unrecognized function or variable 'a'. is there a way to address this?
Luke Simonson
2022 年 1 月 21 日
You need to initialize a as a variable before you set a = a+1.
a = 0;
a = a+1;
Walter Roberson
2013 年 12 月 24 日
You could create a class with preincrement and postincrement methods.
8 件のコメント
Francois Deneuville
2019 年 4 月 17 日
By the way, Walter, thanks for you comment:
You could create a class with preincrement and postincrement methods.
it was a great idea
Jesús Ramos
2021 年 5 月 29 日
What you implemented is the ++i operator of C (or java), where the variable is increased before returning the value, if you want to implement the i++ operator, you would have to add another method to the class:
function out = post_add(self)
temp=self.i;
self.i=self.i+1;
out=temp;
end
参考
カテゴリ
Help Center および File Exchange で Function Creation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!