Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data arrangement in vector

Tags:

vector

matlab

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?

like image 769
Div Avatar asked May 19 '26 18:05

Div


1 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.

like image 78
Thomas Sablik Avatar answered May 21 '26 10:05

Thomas Sablik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!