matlab - 向量中的数据排列

标签 matlab vector

我有以下向量:

enter image description here

下面是生成这个向量的代码:

A = [11 115 167 44 51 5 6];
B = [100 1 1 87];
C = [2000 625];
D = [81 623 45 48 6 14 429 456 94];
E = [89];
F = [44 846 998 2035 498 4 68 4 1 89];

G = {A,B,C,D,E,F};

[max_val, idx] = max(cellfun(@numel, G)); % Find max sizes of vectors

% Create vector with zeros filling open matrix space
LeftIndented = zeros(idx,max_val);
for k = 1:numel(G), LeftIndented(k,1:numel(G{k})) = G{k}; end

我想要一个向量:

  1. 右边的数据(左边的零)

enter image description here

  1. 居中数据(用零包围)

enter image description here

(注意,如果数据不能完全居中,向左偏移一个向量空间也是可以的)

我怎样才能做到这一点?

最佳答案

您可以用零填充每个向量:

A = [11 115 167 44 51 5 6];
B = [100 1 1 87];
C = [2000 625];
D = [81 623 45 48 6 14 429 456 94];
E = [89];
F = [44 846 998 2035 498 4 68 4 1 89];

G = {A,B,C,D,E,F};

[max_val, idx] = max(cellfun(@numel, G)); % Find max sizes of vectors

% Create vector with zeros filling open matrix space
LeftIndented = zeros(idx,max_val);
Centered = zeros(idx,max_val);
RightAligned = zeros(idx,max_val);
for k = 1:numel(G)
    LeftIndented(k,1:numel(G{k})) = G{k};
    l = length(G{k});
    padding = max_val - l;
    leftPadding = floor(padding / 2);
    Centered(k, :) = [zeros(1, leftPadding), G{k}, zeros(1, padding - leftPadding)];
    RightAligned(k, :) = [zeros(1, padding), G{k}];
end

这相当于

A = [11 115 167 44 51 5 6];
B = [100 1 1 87];
C = [2000 625];
D = [81 623 45 48 6 14 429 456 94];
E = [89];
F = [44 846 998 2035 498 4 68 4 1 89];

G = {A,B,C,D,E,F};

[max_val, idx] = max(cellfun(@numel, G)); % Find max sizes of vectors

% Create vector with zeros filling open matrix space
LeftIndented = zeros(idx,max_val);
Centered = zeros(idx,max_val);
RightAligned = zeros(idx,max_val);
for k = 1:numel(G)
    LeftIndented(k,1:numel(G{k})) = G{k};
    l = length(G{k});
    padding = max_val - l;
    leftPadding = floor(padding / 2);
    Centered(k, 1 + leftPadding:leftPadding + l) = G{k};
    RightAligned(k, 1 + padding:end) = G{k};
end

但在第二个代码中,向量的值被写入零向量中的正确位置。

关于matlab - 向量中的数据排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65823310/

相关文章:

matlab - 通过平均在 Matlab 中对数据进行下采样

matlab - 使用 caffe 提取过滤器和偏差

c++ - 将文件读入 vector ,我的输入函数有什么问题?

c++ - std::set_intersection,带偏移量的交集列表

Matlab:对图像求导有困难吗?

matlab - Simulink中的三阶速率限制器?如何产生平滑的触发信号?

C++ 指针 vector 如何影响性能?

c++ - 大小在运行时确定的静态数组 vector

C++ 用更多元素重写浮点 vector

c - 在Matlab中调用库函数时出现奇怪/奇怪的字符