MATLAB Answers

How do I create a for loop in MATLAB?

12 429 views (last 30 days)
I am completely lost in for loops, I just don't get it. The book and my professor haven't helped much. Where can I get help?
  2 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 5 Mar 2012
Edited: MathWorks Support Team on 9 Nov 2018
A basic for loop in MATLAB is often used to assign to or access array elements iteratively. For example, let’s say you have a vector A, and you want to simply display each value one at a time:
A = [3 6 9 4 1];
for i = 1:length(A)
disp(A(i))
end
For more examples using for loops, see:
  3 Comments
Walter Roberson
Walter Roberson on 3 Sep 2021
Not sure why it is said that it doesn't work?
A = [3 6 9 4 1];
for i = 1:length(A)
disp(A(i))
end
3 6 9 4 1

Sign in to comment.

More Answers (5)

Jan
Jan on 5 Mar 2012
You can get help from the documentation of Matlab:
doc for
help for
There you find examples and explanations.
  1 Comment
Meenakshi Bhardwaj
Meenakshi Bhardwaj on 19 Jul 2018
Thanks so much. Finally, I understood what is for loop.

Sign in to comment.


Jan Afridi
Jan Afridi on 29 Sep 2017
For loop repeat itself for a given number of input. The syntax for “For Loop Matlab” is
for variable = expression
Program Statement
end
In the above syntax, the expression has one of the following forms.
Initial value : Final value
for x = 1:10
fprintf('value of x: %d\n', x);
end
Initial value : Step : Final value
for x = 1:2:10
fprintf('value of x: %d\n', x);
end
Value Array
for x = [1 4 6 8 90]
disp(x)
end
To learn more about in detail visit this link For Loop Matlab

Annesha Ahsan
Annesha Ahsan on 4 Jan 2019
for i=1:2:10
UnablEto get the answer

mohamed mohamed
mohamed mohamed on 6 Feb 2021
Edited: Walter Roberson on 31 Jul 2021
for x = 1:10
fprintf('value of x: %d\n', x);
end
value of x: 1 value of x: 2 value of x: 3 value of x: 4 value of x: 5 value of x: 6 value of x: 7 value of x: 8 value of x: 9 value of x: 10

Community Treasure Hunt

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

Start Hunting!