# Hello everyone. How to make a matrix with unequal number of rows and columns, and make the number of rows and columns the same by adding zeros. Thank you very much.

조회 수: 9(최근 30일)
Wesley 2021년 5월 31일
댓글: Image Analyst 2021년 5월 31일
How to make a matrix with unequal number of rows and columns, and make the number of rows and columns the same by adding zeros.

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

### 채택된 답변

Rik 2021년 5월 31일
This isn't too difficult, as Matlab automatically fills an array with zeros as it is expanded.
dataA=S.dataA;size(dataA)
ans = 1×2
375 2
dataB=S.dataB;size(dataB)
ans = 1×2
395 2
%Store them in a cell:
c={dataA,dataB};
max_sz=max(cellfun('size',c(:).',1));
for n=find(cellfun('size',c(:).',1) < max_sz)
c{n}(max_sz,1)=0;
end
max_sz=max(cellfun('size',c(:).',2));
for n=find(cellfun('size',c(:).',2) < max_sz)
c{n}(1,max_sz)=0;
end
c
c = 1×2 cell array
{395×2 double} {395×2 double}
What you do from here is up to you.

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

### 추가 답변(2개)

Image Analyst 2021년 5월 31일
Try this:
a = rand(5, 2);
% Get longest dimension.
longestDimension = length(a)
% Make rows and columns of a both be longestDimension by adding zeros:
a(longestDimension, longestDimension) = 0 % Expand shortest dimension.
whos a % Show size in command window
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

Mathieu NOE 2021년 5월 31일
hello
see example code below
clearvars;
[m,n] = size(dataA);
if m>=n
out = zeros(m,m);
out(1:m,1:n) = dataA;
else
out = zeros(n,n);
out(1:m,1:n) = dataA;
end
##### 댓글 수: 5표시숨기기 이전 댓글 수: 4
Image Analyst 2021년 5월 31일
Ha - no Rik. Actually last time I looked there were only two Answers - yours was not there. Actually I admire people who know the cryptic ways of doing things because they're often something I cannot do or understand. It's just that often/usually I give code that looks longer because I have long descriptive variable names and lots of comments and I usually lose out to those who come along with a one liner of alphabet soup because the poster liked that it was very short. However they often come back with something like "well it works but I don't understand it so can you explain it?".

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

### Community Treasure Hunt

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

Start Hunting!

Translated by