Converting to a square matrix

28 vues (au cours des 30 derniers jours)
med-sweng
med-sweng le 19 Fév 2014
Commenté : Image Analyst le 20 Fév 2014
In `MATLAB`, say that we have a matrix with the following dimensions:
[11036,1]
How can we convert that to a square matrix?
Thanks.

Réponse acceptée

Jos (10584)
Jos (10584) le 19 Fév 2014
N = numel(MyMatrix)
N2 = ceil(sqrt(N))
if N2^2 > N
MyMatrix(N2^2) = 0 % pads with zeros if needed
end
MyMatrix = reshape(MyMatrix,N2,N2) % square!
  1 commentaire
med-sweng
med-sweng le 19 Fév 2014
Thanks a lot Jos. Very nice answer!

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 19 Fév 2014
Since sqrt(11036) is not an integer, are you okay with clipping off some elements?
aNew = a(1:(105*105)); % Extract the proper number of elements.
aNew = reshape(a, [105, 105]); % Make 2D square.
  2 commentaires
med-sweng
med-sweng le 19 Fév 2014
Thanks for your reply. Isn't there an automatic way to do that? And, can padding by "0" for instance be done for filling the empty elements?
Image Analyst
Image Analyst le 20 Fév 2014
Yes, looks like Jos answered before I could. I'm not sure if you knew in advance that the matrix could not be square when you asked, but if you did, you could have gotten a quicker answer if you had specified whether to clip or pad in your original question. I assumed the clipping option when you evidently wanted the padding option. I guess I could have guessed at both ways but it would be better if you just state all your requirements up front so we don't have to guess.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by