loop over a list of numbers
Show older comments
I would like to run a loop over a list of numbers like {3,6,18}. Please advise.
Accepted Answer
More Answers (3)
Muhammad Asad
on 21 Dec 2018
for i = [3, 6,18]
%do something
end
1 Comment
Raphaël Nussbaumer
on 29 Sep 2023
Edited: Raphaël Nussbaumer
on 29 Sep 2023
Just a note for those of you that make the same mistake. the list needs to be row vector and it doesn't work with column vector such as:
for i = [3, 6,18]'
%do something
end
Walter Roberson
on 8 Apr 2018
for K=[3, 6,18]
Note: you will find that often you turn out to need a different structure,
kvals = [3,6,18];
numk = length(kvals);
results = zeros(1, numk);
for kidx = 1 : numk
K = kvals(kidx) ;
....
results(kidx) =....
end
You would need this kind of structure when you need one output for each of the different values.
1 Comment
alpedhuez
on 12 Apr 2018
Shivani Dixit
on 1 Jun 2021
For looping over each element of an array or list , you can use for loop or while loop according to convenience. Simply using a for loop would answer your question.
given_array=[3,6,18];
len =length(given_array)
for i=1:len
% some operation here or access the array elements using given_array(i)
end
You can leverage the documentation for loops using
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!