how to create vector 1 1 1 1 1 1 2 2 2 2 2 2?

12 ビュー (過去 30 日間)
lior
lior 2024 年 7 月 27 日
コメント済み: Stephen23 2024 年 7 月 27 日
I wasn't given any function or limitation on this, however I just started learning about this(part of my HB after first lesson) and I'd love if someone can show me a simple and effective way to create a vector that looks like 1 1 1 1 1 1 2 2 2 2 2 2

回答 (3 件)

Torsten
Torsten 2024 年 7 月 27 日
移動済み: Torsten 2024 年 7 月 27 日
v = [1 1 1 1 1 1 2 2 2 2 2 2]
  2 件のコメント
lior
lior 2024 年 7 月 27 日
is there a shorter way? like the way I can write 1:12 and it just writes that?
Stephen23
Stephen23 2024 年 7 月 27 日
ceil((1:12)/6)
ans = 1x12
1 1 1 1 1 1 2 2 2 2 2 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
repelem(1:2,6)
ans = 1x12
1 1 1 1 1 1 2 2 2 2 2 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

サインインしてコメントする。


Umar
Umar 2024 年 7 月 27 日
移動済み: Voss 2024 年 7 月 27 日

Hi lior,

Try using the repelem function. This function repeats each element of an input vector a specific number of times. Here's how you can achieve the desired vector:

% Define the elements to repeat

elements = [1 2];

% Define the number of repetitions for each element

repetitions = [6 6];

% Create the vector with repeated elements

result_vector = repelem(elements, repetitions);

% Display the result

disp(result_vector);

So, first define the elements [1 2] that you want to repeat and the number of repetitions [6 6] for each element, use repelem function to generate the vector result_vector with the desired pattern. Finally, use disp to display the result. Please see attached results.

Hope, this answers your question.


Star Strider
Star Strider 2024 年 7 月 27 日
An alternative approach —
v = reshape(ones(6,1)*[1 2],1,[])
v = 1x12
1 1 1 1 1 1 2 2 2 2 2 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by