필터 지우기
필터 지우기

Insert specific number of rows of zeroes(5) after every 56 rows in my n*m matrix. I am able to create matrices but can I do the insertion without loop given I know the size of matrix? Thanks for help

조회 수: 1 (최근 30일)
I have a huge 2464 * 2484 matrix that I want to manipulate and make 2684*2684 but I need the new 220 rows to be divided into 5 rows after every 56 rows of original matrix. I am able to think of loop code --
>> A=csvread('InputWIODRaw.csv');
>> A=csvread('InputWIODRaw.csv');
>> B= zeros(5,2684);
>> CountryVar = [56:56:2464];
>> for i = 1:44
if i==1
j=1;
elseif i>1
j=CountryVar(i-1)+1;
end
ReorderMatrix(i)= A(j:CountryVar(i),:);
Reorder(i) = [ReorderMatrix(i); B];
end
error: =: nonconformant arguments (op1 is 1x1, op2 is 56x2684)
>> for i = 1:44
if i==1
j=1;
elseif i>1
j=CountryVar(i-1)+1;
end
ReorderMatrix(i) = zeros(56,2684);,2684)= A(j:CountryVar(i),:);
parse error:
syntax error
>>> ReorderMatrix(i) = zeros(56,2684);,2684)= A(j:CountryVar(i),:);
^
>> ReorderMatrix(i) = zeros(56,2684);
error: =: nonconformant arguments (op1 is 1x1, op2 is 56x2684)
But not sure how to initialize. Is there a better way if not how to rectify this code? Much appreciated

채택된 답변

Kelly Kearney
Kelly Kearney 2018년 3월 22일
Another approach, which works even if your data doesn't divide evenly:
x = rand(21,6);
nrow = 5; % number of rows of data in each group
nlines = 2; % number of rows of 0s to add after each group
nsets = floor(size(x,1)./nrow);
nextra = rem(size(x,1), nrow);
x = mat2cell(x, [ones(nsets,1)*nrow; nextra], size(x,2));
x = cellfun(@(x) [x; zeros(nlines, size(x,2))], x, 'uni', 0);
x = cat(1, x{:});

추가 답변 (1개)

Guillaume
Guillaume 2018년 3월 22일
You can indeed do it without a loop.
  1. transpose the matrix so that your rows are columns (since matlab works by column)
  2. reshape the matrix so that each group of your original 56 rows are now a single column. Thus you end up with a matrix of 44 columns
  3. vertically concatenate this reshaped matrix with a zero matrix of height 5*width of original matrix and of width 44
  4. reshape the result back into the right number of rows and columns and transpose back
A = csvread('InputWIODRaw.csv');
B = A.';
B = reshape(B, 56*size(A, 2), []);
B = [B; zeros(5*size(A, 1), size(B, 2))];
B = reshape(B, size(A, 2), []);
B = B.';
  댓글 수: 1
Siddhartha Sharma
Siddhartha Sharma 2018년 3월 23일
Thanks Guillaume, Although due to some reason the reshape size is throwing errors and the reverse transpose is not happening so I end up with 16800 columns.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by