loop over a list of numbers

1,693 次查看(过去 30 天)
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})
end

更多回答(3 个)

Muhammad Asad
Muhammad Asad 2018-12-21
for i = [3, 6,18]
%do something
end
  1 个评论
Raphaël Nussbaumer
编辑:Raphaël Nussbaumer 2023-9-29
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
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) =....
end
You would need this kind of structure when you need one output for each of the different values.

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.
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by