Repeat copies of array elements using for loop/while

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 个评论

Why? You didn't tag it as homework so since it's not your homework why won't you use repelem()?
The logic my friend, its too easy use the matlab functions, I want create my owns functions. For example, I create my own functions to find max and min values from arrays (and I know the max and min function exist). I need understand the logic, because with that logic I can repeat a code in others lenguajes. (by the way, sorry for my english).
Note: It's not homework.
OK, if you want to create your own, then I'll let you do it. I'll just give a hint if you want it. The index "i" in the loop should be a vector of length 2 that specifies a starting and stopping index, like instead of 2 it should be [3:4].
Got it, but i don't understand where I defind the index. I try this:
for i = 1:3
Vec([i+1:i+2]) = i;
end
And I know I need to find an index that in iteration 1 is like:
[1:2]
and the second iteration is:
[3:4]
But i don´t have idea. Another clue?
What if you subtract 1 from i before multiplying it by 2?
Finally I figured out. Thank you. Got it:
for i =1:4
Vec((2*i)-1:i*2) = i;
end

请先登录,再进行评论。

 采纳的回答

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 个)

类别

帮助中心File 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