convert a vector to 2D matrix

5 views (last 30 days)
Hi all
How do I convert a vector into a two-dimensional matrix like this?
A=[1 2 3 4 5 6 7]
A=[ 1 2 3
4 5 6
7 0 0]

Accepted Answer

Image Analyst
Image Analyst on 18 Jul 2021
This will do it without any toolboxes:
A=[1 2 3 4 5 6 7]
columnsInA = size(A, 2);
% We want a square matrix. So figure out many rows or columns there must be
columnsInOutput = ceil(sqrt(columnsInA))
% So make it a row vector numColumns * numColumns elements long.
A((columnsInA + 1) : columnsInOutput^2) = 0 % Pad with zeros
% Now reshape into numColumns columns or rows:
A = reshape(A, columnsInOutput, [])'
A =
1 2 3 4 5 6 7 0 0
A =
1 2 3
4 5 6
7 0 0
I didn't know if you wanted it in general to have 3 columns or 3 rows, or be square. There are slight modifications depending on the input A and the answer to that question.

More Answers (1)

Walter Roberson
Walter Roberson on 18 Jul 2021
buffer(A, 3).'
This requires the Communications System Toolbox
  4 Comments
Walter Roberson
Walter Roberson on 19 Jul 2021
Questions for you:
If, hypothetically, MATLAB did permit "holes" in arrays, then how should that work?
In the below, if we let a "hole" be represented by H, then what should be the result of:
[1 H] + [H 2]
[1 H] .* [H 2]
exp(H)
mean([2 4 H]) %is that (2+4)/2 or is that (2+4)/3 ?
inv([2 0; 0 H])
inv([2 0 H; 0 2 H; H H H]) %should that be [1/2 0 H; 0 1/2 H; H H H] -- inverse of the part that is not holes?
Should
sum([2 3 4]) == sum([7 H H]) %or should there be a way to distinguish the two?
Should a hole be treated the same as NaN for mathematical purposes? Should there be any difference between NaN and holes, other than that holes display empty? If you have
[1 H 2]
then how should that display? Should you count on people knowing what the current "format" is, and how many spaces would normally be present? "format long" normally has more blanks between entries than "format short" does, so if you put spaces in instead of holes, then will users be able to reliably figure out that
1 2
is
[1 H H 2]
displayed in format long, and not
[1 H H H 2]
displayed in format short?
Your sample output tends to suggest that you want the right-hand-side display of entries to "collapse" around all holes. But if so then how is the user intended to tell the difference between
1 2 H
3 4 H
and
1 2
3 4
??

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by