MATLAB Answers

How to combine the result of for loop?

4 views (last 30 days)
Here is a very simple line of code:
x = 3;
A = 1:x;
for i = 1:length(A)
y = repelem(A(:,i),i);
Y = y(1,:)
end
I want to generate result in the form
[1 2 2 3 3 3]
What I am doing mistake, please help me in this regard. Thanks

  3 Comments

Mirlan Karimov
Mirlan Karimov on 12 May 2020
You overwrite Y, that is the problem.
Mirlan Karimov
Mirlan Karimov on 12 May 2020
x = 3;
A = 1:x;
Y = [];
for i = 1:length(A)
y = repelem(A(:,i),i);
Y(length(Y)+1:length(Y)+1 +length(y)-1) = y(1,:)
end
Muhammad Usman
Muhammad Usman on 12 May 2020
Can you please suggest me how to write?

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 12 May 2020
>> A = 1:3;
>> repelem(A,1,A)
ans =
1 2 2 3 3 3

  1 Comment

Muhammad Usman
Muhammad Usman on 12 May 2020
Thank you so very much, very efficient

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by