How can I reshape single column vector list into equally sized matrix columns

조회 수: 8 (최근 30일)
Hi,
I have a single column vector variable with a list of 26599 elements. I want to reshape this list into a matrix of equally sized columns of 512. The issue is that the number 26599 isn't divisible by 512 and so I get an error. Hence, I want to reshape the vector into matrix colums where all columns have the size of 512 except for the last one.
How would I go about doing this?
I tried the reshape function but that didnt work because of the issue mentioned above.
>> R = reshape(sample_test,512,[]);
Error using reshape
Product of known dimensions, 512, not divisible into total number of elements, 26599.
Thank you!

채택된 답변

Voss
Voss 2022년 1월 9일
You can't have a matrix with different size columns, but you could fill the last column with NaNs:
sample_test = ones(520,1);
% append NaNs to sample_test up to the next multiple of block_size
block_size = 512;
N = block_size*ceil(numel(sample_test)/block_size);
sample_test(end+1:N) = NaN;
R = reshape(sample_test,512,[])
R = 512×2
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 NaN 1 NaN
  댓글 수: 5
Voss
Voss 2022년 1월 9일
You can make sample_test a column vector like this:
sample_test = sample_test(:);
and then use my code on that.

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

추가 답변 (1개)

Torsten
Torsten 2022년 1월 9일
편집: Torsten 2022년 1월 9일
s = mod(26599,512);
n = 26599 - s;
m = n/512;
R = horzcat(reshape(sample_test(1:n),512,m),vertcat(sample_test(n+1:end),NaN(512-s,1)));
  댓글 수: 2
lil brain
lil brain 2022년 1월 9일
When running this code I get the error:
Index exceeds the number of array elements (1040).
What am I doing wrong?

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by