loop over a list of numbers

3,192 ビュー (過去 30 日間)
alpedhuez 2018 年 4 月 8 日
回答済み: Shivani Dixit 2021 年 6 月 1 日
I would like to run a loop over a list of numbers like {3,6,18}. Please advise.


Star Strider
Star Strider 2018 年 4 月 8 日
The loop, if one is appropriate, depends on what you want to do.
This is an example of how to address them:
numlist = {3,6,18};
for k1 = 1:length(numlist)
fprintf('Number at position %d = %6.2f\n', k1, numlist{k1})

その他の回答 (3 件)

Muhammad Asad
Muhammad Asad 2018 年 12 月 21 日
for i = [3, 6,18]
%do something

Walter Roberson
Walter Roberson 2018 年 4 月 8 日
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) =....
You would need this kind of structure when you need one output for each of the different values.
  1 件のコメント
alpedhuez 2018 年 4 月 12 日
Thank you.


Shivani Dixit
Shivani Dixit 2021 年 6 月 1 日
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.
len =length(given_array)
for i=1:len
% some operation here or access the array elements using given_array(i)
You can leverage the documentation for loops using



Community Treasure Hunt

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

Start Hunting!

Translated by