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)
Show older comments
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
on 19 Aug 2023
Not an answer to this question, but perhaps useful to someone:
n = 5;
v = repelem(1:n,1:n)
Accepted Answer
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).
0 Comments
More Answers (0)
See Also
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!