Repeat copies of array elements using for loop/while

조회 수: 7 (최근 30일)
Juan Pérez Álvarez
Juan Pérez Álvarez 2022년 2월 26일
답변: Image Analyst 2022년 2월 27일
Hi, I need create a code where the elements of an array are repeat:
For example:
% Create a simple vector:
for i =1:4
Vec(i) = i;
end
Vec = [1,2,3,4];
If I need repeat the elements of this vector 2 times:
Vec = [1,1,2,2,3,3,4,4];
3 times:
Vec = [1,1,1,2,2,2,3,3,3,4,4,4];
I know using the function: repelem; I can get this result but I need do it using a for loop/while.
¿Any idea?
  댓글 수: 6
Image Analyst
Image Analyst 2022년 2월 27일
What if you subtract 1 from i before multiplying it by 2?
Juan Pérez Álvarez
Juan Pérez Álvarez 2022년 2월 27일
편집: Image Analyst 2022년 2월 27일
Finally I figured out. Thank you. Got it:
for i =1:4
Vec((2*i)-1:i*2) = i;
end

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

채택된 답변

Image Analyst
Image Analyst 2022년 2월 27일
I'd do it slightly differently:
Vec = 1 : 4;
n = 3; % Number of times to repeat each element of Vec
Vec2 = zeros(1, 2 * length(Vec));
for k = 1 : length(Vec)
index1 = (k-1) * n + 1;
index2 = index1 + n - 1;
Vec2(index1 : index2) = Vec(k);
end
Vec2

추가 답변 (0개)

카테고리

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

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by