Inserting new element after each element of an array

13 ビュー (過去 30 日間)
Neeraj Chimwal
Neeraj Chimwal 2021 年 3 月 25 日
編集済み: DGM 2021 年 3 月 26 日
I have an array arr = [2,4,6]
After converting this array elements to binary using de2bi(arr,'left-msb'), I get
0 1 0
1 0 0
1 1 0
Now what I want to do is to insert 0 after each 0 and 1 after each 1. So the result would be
0 0 1 1 0 0
1 1 0 0 0 0
1 1 1 1 0 0
I tried looping through the array, but since length of binary array is still 3, I can't loop through each element.
Can anyone please help me with this?

採用された回答

Stephen23
Stephen23 2021 年 3 月 25 日
The MATLAB approach:
arr = [2,4,6];
mat = repelem(de2bi(arr,'left-msb'),1,2)
mat = 3×6
0 0 1 1 0 0 1 1 0 0 0 0 1 1 1 1 0 0

その他の回答 (2 件)

David Goodmanson
David Goodmanson 2021 年 3 月 25 日
編集済み: David Goodmanson 2021 年 3 月 25 日
Hi Neeraj,
not having the communications toolbox I used dec2bin instead, which gives a character array but it is basically the same idea and should work on a binary array I would think.
arr = [2,4,6];
a = dec2bin(arr)
s1 = size(a,1);
s2 = size(a,2);
c(1:s1,1:2:2*s2) = a;
c(1:s1,2:2:2*s2) = a
  2 件のコメント
Neeraj Chimwal
Neeraj Chimwal 2021 年 3 月 25 日
that worked. If you don't mind can you please explain me the last two steps
David Goodmanson
David Goodmanson 2021 年 3 月 26 日
Hi Neeraj,
The index 1 : 2*s2 is twice as large as the number of columns in 'a'.
In the first step, by using 1:2:2*s2, 'a' is inserted into the odd numbered columns of the new matrix.
In the 2nd step, by using 2:2:2*s2, 'a' is inserted into the even numbered columns of the new matrix.

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


DGM
DGM 2021 年 3 月 25 日
You should be able to loop through the array regardless of its size. That said, you don't need to.
A=[1 2 3 4];
B=dec2bin(A);
expanded=B(:,round(0.5:0.5:size(B,2)));
which gives:
expanded =
000011
001100
001111
110000
  2 件のコメント
Neeraj Chimwal
Neeraj Chimwal 2021 年 3 月 25 日
that worked. Can you please explain the last step? I didn't understand what 0.5:0.5 did here
DGM
DGM 2021 年 3 月 26 日
編集済み: DGM 2021 年 3 月 26 日
This bit:
0.5:0.5:size(B,2)
generates a vector like so:
[0.5 1.0 1.5 2.0 2.5 3.0 ... ]
rounding that vector gives us this:
[1 1 2 2 3 3 ... ]
so that we're referencing each element of B twice
Alternatively, you could use something like kron() to generate the same index vector:
kron([1 2 3 4],[1 1])
would yield
[1 1 2 2 3 3 4 4 ]

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

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by