Borrar filtros
Borrar filtros

How to increment a variable

1.601 visualizaciones (últimos 30 días)
KHADIJA
KHADIJA el 24 de Dic. de 2013
Comentada: John D'Errico el 14 de Sept. de 2022
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.

Respuesta aceptada

John D'Errico
John D'Errico el 26 de Ag. de 2016
Editada: MathWorks Support Team el 22 de Mayo de 2019
To increment a variable X, simply use
X = X+1;
MATLAB does not support the increment operator ++.
  12 comentarios
Jan
Jan el 14 de Sept. de 2022
No, you can't do this in Matlab.
John D'Errico
John D'Errico el 14 de Sept. de 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.

Iniciar sesión para comentar.

Más respuestas (2)

Wayne King
Wayne King el 24 de Dic. de 2013
Editada: Walter Roberson el 21 de En. de 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 comentarios
Nivethana Narayanan
Nivethana Narayanan el 28 de Nov. de 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
Luke Simonson el 21 de En. de 2022
You need to initialize a as a variable before you set a = a+1.
a = 0;
a = a+1;

Iniciar sesión para comentar.


Walter Roberson
Walter Roberson el 24 de Dic. de 2013
You could create a class with preincrement and postincrement methods.
  8 comentarios
Francois Deneuville
Francois Deneuville el 17 de Abr. de 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
Jesús Ramos el 29 de Mayo de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Function Creation en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by