Data arrangement in vector

Viewed 44

I have the following vector:

enter image description here

Here is the code to produce this vector:

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

I would like to have a vector with:

  1. Data to the right (zeros to the left)

enter image description here

  1. Centered data (surrounded with zeros)

enter image description here

(Notice that if data cannot be exactly centered, it is ok if it is off by one vector space to the left)

How can I achieve this?

2 Answers

You can pad each vector with zeros:

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

This is equivalent to

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

but in the second code the values of the vectors are written into the correct position in a zero vector.

A solution using strjust:

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};

data = [G{:}];
N = cellfun(@numel, G);
M = max(N);
idx = char((N.' >= (1:M))+32); 

Le = strjust(idx, 'left');
Ri = strjust(idx, 'right');
Ce = strjust(idx, 'center');

LeftAdjusted = zeros(M, N);
RightAdjusted = zeros(M, N);
Centered = zeros(M, N);

LeftAdjusted(Le.' ~= ' ') = data;
RightAdjusted(Ri.' ~= ' ') = data;
Centered(Ce.' ~= ' ') = data;

LeftAdjusted = LeftAdjusted.';
RightAdjusted = RightAdjusted.';
Centered = Centered.';
Related