How to increment a variable
433 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
Risposta accettata
John D'Errico
il 26 Ago 2016
Modificato: MathWorks Support Team
il 22 Mag 2019
To increment a variable X, simply use
X = X+1;
MATLAB does not support the increment operator ++.
13 Commenti
John D'Errico
il 14 Set 2022
@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.
Rev
il 12 Apr 2025
The one thing about being able to use syntax like C++ (the increment operation) is that when you want to try out ideas or concepts, Matlab makes it easier to test out sub sections of code instead of trying to compile and run it. It is helpful to be able to implement other language syntax in my experience. Matlab let's us try out code snippets and test out DSP operations with real time interface to hardware and equipment. Not to mention not having deal with the compiler.
Più risposte (2)
Wayne King
il 24 Dic 2013
Modificato: Walter Roberson
il 21 Gen 2022
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 Commenti
Nivethana Narayanan
il 28 Nov 2021
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
il 21 Gen 2022
You need to initialize a as a variable before you set a = a+1.
a = 0;
a = a+1;
Walter Roberson
il 24 Dic 2013
You could create a class with preincrement and postincrement methods.
8 Commenti
Francois Deneuville
il 17 Apr 2019
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
il 29 Mag 2021
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
Vedere anche
Categorie
Scopri di più su Performance and Memory in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!