How can I generate a vector like this 1,2,2,3,3,3,4,4,4,4 by using for loop?

6 views (last 30 days)
Hi all,
There's a problem that asks to generate a vector like 1,2,2,3,3,3,4,4,4,4
So if the input n = 5, then the output = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
I tried to solve it by using for loop
but I couldn't find a way to do this
function y = your_fcn_name(n)
L = length((n^2+n)/2)
for i = 1:L
end
I don't know what should I do inside the for loop, I tried to get the relation between the value and its index in the vector, but I couldn't
can you help me solve this problem with a for loop?
  3 Comments
Stephen23
Stephen23 on 19 Aug 2023
Not an answer to this question, but perhaps useful to someone:
n = 5;
v = repelem(1:n,1:n)
v = 1×15
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

Sign in to comment.

Accepted Answer

Torsten
Torsten on 18 Aug 2023
Moved: Image Analyst on 19 Aug 2023
Start with y = [] and in each step of the for-loop running from 1 to n, concatenate y and i*ones(1,i).

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!