MATLAB:通过将最后一行添加到基本矩阵的第一行来获得矩阵

MATLAB : Obtain a matrix by adding its last lines to the first lines of the basic matrix

我有一个矩阵 B,我想通过将最后 w*a 行添加到第一个 [=14] 从 B 获得一个新矩阵 C =] 行(wa 将在之后定义)。

我的矩阵 B 通常定义为:

我想通过以下方式获得以一般方式定义的矩阵 C

矩阵BC的特征是:

示例:对于L = 4w = 2,我得到以下矩阵B

Bw*a = 2*1 = 2 最后一行是:

Bw*a = 2*1 = 2 第一行是:

将两个矩阵相加得到:

这样得到的矩阵C则为:

对于 B0 = [1 0]B1 = [0 1]B2 = [1 1]。我们得到:

得到的矩阵BC如下:

B = 

    1    0    0    0    0    0    0    0
    0    1    1    0    0    0    0    0
    1    1    0    1    1    0    0    0
    0    0    1    1    0    1    1    0
    0    0    0    0    1    1    0    1
    0    0    0    0    0    0    1    1

C = 

    1    0    0    0    1    1    0    1
    0    1    1    0    0    0    1    1 
    1    1    0    1    1    0    0    0
    0    0    1    1    0    1    1    0 

我想就如何对这个构造进行编程提出一些建议,以便从给定的矩阵 B 我可以推导出矩阵 C

Matlab 的 range indexing 应该可以帮助您通过几个步骤完成此操作。要记住的关键是范围是包容性的,即 A[1:3] 是一个三个 3x1 矩阵,您可以使用关键字 end 自动索引矩阵行或列的末尾。

%% Variables from OP example

w = 2;
L = 4;

B0 = [1 0];
B1 = [0 1];
B2 = [1 1];
[a, b] = size(B0);

% Construct B
BX = [B0;B1;B2]
B = zeros((L+w)*a, L*b);
for ii = 0:L-1
   B(ii+1:ii+w+1, ii*b+1:ii*b+b) = BX;
end

%% Construct C <- THIS PART IS THE ANSWER TO THE QUESTION

% Grab first rows of B
B_first = B(1:end-w*a, :) % Indexing starts at first row, continues to w*a rows before the end, and gets all columns
% Grab last rows of B
B_last = B(end-w*a+1:end, :); % Indexing starts at w*a rows before the end, continues to end. Plus one is needed to avoid off by one error. 
% Initialize C to be the same as B_first
C = B_first;
% Add B_last to the first rows of C
C(1:w*a, :) = C(1:w*a, :) + B_last;

我得到输出

C =

     1     0     0     0     0     0     1     1     0     1
     0     1     1     0     0     0     0     0     1     1
     1     1     0     1     1     0     0     0     0     0
     0     0     1     1     0     1     1     0     0     0
     0     0     0     0     1     1     0     1     1     0