How to increment a variable

조회 수: 440 (최근 30일)
KHADIJA
KHADIJA 2013년 12월 24일
댓글: Rev 2025년 4월 12일
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.
  댓글 수: 1
amit dehury
amit dehury 2019년 8월 28일
variable=variable+1

댓글을 달려면 로그인하십시오.

채택된 답변

John D'Errico
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 ++.
  댓글 수: 13
John D'Errico
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.
Rev
Rev 2025년 4월 12일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Wayne King
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
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
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
Walter Roberson 2013년 12월 24일
You could create a class with preincrement and postincrement methods.
  댓글 수: 8
Francois Deneuville
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
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 CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by