How do I create a for loop in MATLAB?
6 131 views (last 30 days)
Show older comments
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?
Accepted Answer
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
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
More Answers (6)
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
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
0 Comments
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
0 Comments
Narasimman P
on 30 Jul 2021
for a=1:10
end
2 Comments
Walter Roberson
on 17 Nov 2021
The code posted by @Narasimman P is a completely valid for loop, just one that does not do anything inside the loop. All it does is count from 1 to 10 internally. After the loop, two things will have changed:
- Time will have elapsed, which could be important if you are waiting for something to happen
- The loop control variable 'a' will have the same value as it was last assigned, so in this case after the loop 'a' will have the double precision value 10 .
disp('before')
whos
disp('starting loop')
for a=1:10
end
disp('after')
whos
So there has been output: the variable a did not exist before, and after the loop it does exist.
Manan Shah
on 8 May 2022
Edited: Torsten
on 8 May 2022
for i = 0:8 ;
a = pow10 (i);
disp a(i);
end
1 Comment
Walter Roberson
on 8 May 2022
disp a(i)
would mean the same thing as
disp('a(i)')
You probably want
disp(a(i))
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!