How do I reshape a large matrix?

조회 수: 4 (최근 30일)
Jewel
Jewel 2018년 7월 12일
편집: dpb 2018년 7월 12일
I am trying to reshape a matrix so that it keeps a consistent amount of columns (8 columns) and the number of rows is ever changing. These rows change because of modifications to number of iterations of a for loop. I know that the correct syntax to use is the reshape function but is it possible to not explicitly state the number of rows and/or columns so that the matrix will automatically reshape to 9 columns and "X" rows? Thanks!

채택된 답변

James Clinton
James Clinton 2018년 7월 12일
I believe you can still use the reshape function for what you are describing. The documentation shows you can input an empty matrix ("[]") to the function so that it will automatically reshape the matrix given a value for the other dimensions of the matrix. Reshaping the 2D matrix "A" into 9 columns would be accomplished by the following:
B = reshape(A,[],9);
nrows = size(B,1);
Where nrows will give you the number of rows the matrix was reshaped into.
Of course this only works when the number of elements is divisible by 9, however. If you'd like to reshape when the number of elements is not divisible by 9 you'll need to pad the matrix with extra numbers. I would do this in the following way (using trailing zeros to pad the matrix):
B = reshape(A,1,[]); % convert A to vector stored in column major format (transpose for row major)
nzeros = rem(size(B,1),ncols); % find the number of zeros needed to pad on the end
C = [B zeros(1,nzeros)]; % add the padding zeros
D = reshape(C,[],ncols); % reshape to have ncols columns
  댓글 수: 2
Jewel
Jewel 2018년 7월 12일
Hi James, I am fairly rusty with my Matlab skills. When you say to find the number of zeros to pad on the end, do you mean adding the correct amount of zeros so therefore the matrix is divisible by 9? If so, is there any way to create an ever changing padding command so that as the matrix changes it is still always divisible by 9? Thank you for your help so far, I know I will have future questions!
Walter Roberson
Walter Roberson 2018년 7월 12일
In another recent question I recently showed this for someone who needed a multiple of 256 rows:
pad_needed = 256 - (mod(size(points,1) - 1, 256) + 1);
if pad_needed > 0
points(end+pad_needed,:) = 0;
end
What I recommend, though, is that if you have the Communications System Toolbox, that you use buffer()

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

추가 답변 (1개)

dpb
dpb 2018년 7월 12일
편집: dpb 2018년 7월 12일
B=reshape(A,[],9);
The kicker is that mod(numel(A),9)==0 or will fail or will have to pad/truncate A.

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by