How to get row and column from a vector size

17 ビュー (過去 30 日間)
Houssam
Houssam 2021 年 6 月 18 日
コメント済み: Houssam 2021 年 6 月 19 日
Hi matlab Community
i am back again with anouther question
i have a vector with variable length like this :
Vector = [10 20 30 40 50 60 70 80 9 100]
> numel(Vector) =
10
or
Vector = [ 1 2 3 4 5 ]
> numel(Vector) =
5
i want to reshape the vector to a matrix with the 2 largest row and coluumn.
but i can't find out how to go from vector size to matrix row and column
thanks in advance
  3 件のコメント
James Tursa
James Tursa 2021 年 6 月 18 日
What do you mean by "2 largest row and column"? Please give examples of reshaped results.
the cyclist
the cyclist 2021 年 6 月 18 日
Also, because 5 is a prime number, your example
Vector = [ 1 2 3 4 5 ];
cannot be shaped into a matrix (other than 1x5 or 5x1), so you might want to clarify that case as well.

サインインしてコメントする。

採用された回答

Scott MacKenzie
Scott MacKenzie 2021 年 6 月 18 日
編集済み: Scott MacKenzie 2021 年 6 月 18 日
Assuming the vector length being a prime number (as noted by @the cyclist) is just one possible case of many, then the following code achieves the desired goal:
% test vector
v = rand(1,randi([1 100]));
n = length(v);
n1 = round(sqrt(n));
while n1 > 1
if ~rem(n,n1)
break;
end
n1 = n1 - 1;
end
n2 = n/n1;
fprintf('For %d elements, max matrix is %d x %d\n', n, n1, n2);
M = reshape(v, n1, n2); % reshaped vector
Output for some example runs:
For 18 elements, max matrix is 3 x 6
For 36 elements, max matrix is 6 x 6
For 44 elements, max matrix is 4 x 11
For 59 elements, max matrix is 1 x 59
  1 件のコメント
Houssam
Houssam 2021 年 6 月 19 日
thanks very mush, this exactly what i was looking for,
but there is always that problem of primary numbers!
so i've decided to to choose 512 as a number of columns
and add zeros at the end of the file so that it can be devided by that number of rows

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by