create vector of repeating elements (sort of)

조회 수: 10 (최근 30일)
Leor Greenberger
Leor Greenberger 2011년 9월 20일
댓글: HC Song 2017년 6월 1일
How can I easily create a vector such that:
w = 3
n = 8
v = (1 w times) (2 w times) (3 w times) ... (n w times)
so i would have:
v = [1 1 1 2 2 2 3 3 3 4 4 4 .... 8 8 8]

채택된 답변

the cyclist
the cyclist 2011년 9월 20일
Here is one way:
w = 3;
n = 8;
v = repmat(1:n,[w 1])
v = v(:)'

추가 답변 (4개)

Oleg Komarov
Oleg Komarov 2011년 9월 20일
For variable w use rude from the fex:
rude(len,val)

Richard Tyson
Richard Tyson 2013년 8월 15일
If you need it to be fast you should avoid using repmat. Stick to C functions which don't need to parse input arguments and do one specific task:
n = 8;
w = 3;
v = ceil( [1:(w*n)]./w )
If anyone has a faster way please post. I do this kind of operation a lot.
  댓글 수: 2
the cyclist
the cyclist 2013년 8월 15일
This thread is nearly two years old. You might want to post this as a new question.
Artur Palha
Artur Palha 2014년 9월 25일
n = 8; w = 3; v = rectpulse(1:n)
This is the fastest option I know of.

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


Lucas García
Lucas García 2011년 9월 20일
One of many ways:
>> w = 3; n = 8;
>> v = repmat(1:n,w,1);
>> v = v(1:end)

Wayne King
Wayne King 2011년 9월 20일
One way:
w = 3;
x = 1:8;
x = arrayfun(@(x) repmat(x,1,w),x,'UniformOutput',false);
x = cell2mat(x);
Wayne
  댓글 수: 1
Jan
Jan 2011년 9월 20일
ARRAYFUN and CELL2MAT needs a lot of time. Using REPMAT directly is much faster.

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

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by