doubt to store a array values in for loop ?

조회 수: 6 (최근 30일)
RAVI MANDAVA
RAVI MANDAVA 2016년 6월 8일
편집: Stephen23 2016년 6월 8일
Dear sir i have doubt to store a array values in for loop. I will explain my code Program:
a=[1 2 3 4 5 6 7 8 9 10]
for i=1:3:10
k(i)=a(i)
end
I need store the values in k variable. i am getting answer k= 1 0 0 3 0 0 6 0 0 9 0 but i need answer like that k=1 3 6 9 is it p[ossible to write the answer like that .
please help me.
  댓글 수: 1
Stephen23
Stephen23 2016년 6월 8일
편집: Stephen23 2016년 6월 8일
MATLAB is a high-level language, so why bother with an ugly loop as if it was just C or something similar? You can do it much neater, faster, and much more efficiently using basic MATLAB indexing:
>> a = [1,2,3,4,5,6,7,8,9,10];
>> b = a(1:3:10)
b =
1 4 7 10
>> c = a(1:2:10)
b =
1 3 5 7 9
Note that I gave two sequences: this is because your output sequence does not have an equal step size (it is not an arithmetic progression), so you cannot generate it using any method that assumes a constant step size (in particular the colon operator). You can check the step size of your solution:
>> diff([1,3,6,9])
ans =
2 3 3

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

답변 (2개)

UNK
UNK 2016년 6월 8일
Hi Ravi, If you have a row vector as a = 1:1:10 and you want only some entries as a new vector you can do b = a([1:3:10])
a = 1:1:10
b = a([1:3:10])
For loops are not efficient. You can look at this which may be useful

Azzi Abdelmalek
Azzi Abdelmalek 2016년 6월 8일
a=[1 2 3 4 5 6 7 8 9 10]
ii=0
for i=1:3:10
ii=ii+1;
k(ii)=a(i)
end

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by