ある行列の各行と行の​間に異なる行列の各行​を割り込ませたい

3 views (last 30 days)
颯太 大山
颯太 大山 on 4 Dec 2024
Commented: 颯太 大山 on 5 Dec 2024
ある行列Aに対して,Aの各行と行の間にB行列の行の値を割り込ませるにはどのようにコーディングすれば簡潔に行えますでしょうか?
例えば
A = zeros(10,1)
B = ones(10,1)
といった行列があった際に,
結果的に
[0;1;0;1;0;1.....0;1]
といった行列にしたいです.

Accepted Answer

Atsushi Ueno
Atsushi Ueno on 4 Dec 2024
reshape 関数が便利です。MATLABは列優先なので、2つの列ベクトルを束ねて転置して輪切りにする様に並べています。
A = zeros(10,1); A' % 列ベクトルを転置して短く表示
ans = 1×10
0 0 0 0 0 0 0 0 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
B = ones(10,1); B'
ans = 1×10
1 1 1 1 1 1 1 1 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
C = reshape([A,B]',[],1); C'
ans = 1×20
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  2 Comments
Akira Agata
Akira Agata on 5 Dec 2024
Edited: Akira Agata on 5 Dec 2024
+1
A, Bが行列の場合は以下のようにすれば可能です。
% 一例として10行4列の行列とします。
A = zeros(10, 4);
B = ones(10, 4);
% 20行4列の行列を作成して、奇数行と偶数行にAとBの値を代入
C = nan(20, 4);
C(1:2:end, :) = A;
C(2:2:end, :) = B;
% 結果を表示
C
C = 20×4
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
颯太 大山
颯太 大山 on 5 Dec 2024
ご回答いただきありがとうございます!
早速教えていただいた方法で試したいと思います!

Sign in to comment.

More Answers (0)

Categories

Find more on ビッグ データの処理 in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!