필터 지우기
필터 지우기

convert a vector to 2D matrix

조회 수: 15 (최근 30일)
reta jon
reta jon 2021년 7월 18일
댓글: Walter Roberson 2021년 7월 19일
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]

채택된 답변

Image Analyst
Image Analyst 2021년 7월 18일
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.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2021년 7월 18일
buffer(A, 3).'
This requires the Communications System Toolbox
  댓글 수: 4
reta jon
reta jon 2021년 7월 18일
thank you so much
Walter Roberson
Walter Roberson 2021년 7월 19일
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
??

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by