# loop over a list of numbers

조회 수: 3,284(최근 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 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개)

for i = [3, 6,18]
%do something
end
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

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.
##### 댓글 수: 1표시숨기기 없음
alpedhuez 2018년 4월 12일
Thank you.

댓글을 달려면 로그인하십시오.

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

댓글을 달려면 로그인하십시오.

### 범주

Find more on Matrix Indexing in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by