Pad empty spaces in matrix with 0

3 ビュー (過去 30 日間)
Meg Cullen
Meg Cullen 2019 年 5 月 12 日
コメント済み: madhan ravi 2019 年 5 月 12 日
I have a matrix of the form:
1 4 6 3 7 3
4 6 2 9
5 5 8 2 5
4 8 1 3 9 4
As I accumulated the rows of the matrix from different sources there is a inconsistency in the length of rows. How do I pad the empty spaces with 0? Please help.
  3 件のコメント
Meg Cullen
Meg Cullen 2019 年 5 月 12 日
編集済み: Meg Cullen 2019 年 5 月 12 日
a = [c1m_wrf(:,3)';c2m_wrf(:,3)';c3m_wrf(:,3)';c4m_wrf(:,3)'];
I created a matrix but since the columns of the different cells are of different length...its not working
Image Analyst
Image Analyst 2019 年 5 月 12 日
What are the "empty spaces" - do you want to just pad the right hand side?

サインインしてコメントする。

採用された回答

Image Analyst
Image Analyst 2019 年 5 月 12 日
Try this:
c1m_wrf = [1 4 6 3 7 3 ]
c2m_wrf = [4 6 2 9]
c3m_wrf = [5 5 8 2 5]
c4m_wrf = [4 8 1 3 9 4 ]
maxLength = max([length(c1m_wrf), length(c2m_wrf), length(c3m_wrf), length(c4m_wrf)])
ca = {c1m_wrf, c2m_wrf, c3m_wrf, c4m_wrf}
m = zeros(4, maxLength);
for row = 1 : length(ca)
thisVector = ca{row};
thisLength = length(thisVector);
m(row, 1:thisLength) = thisVector;
end
You get
m =
1 4 6 3 7 3
4 6 2 9 0 0
5 5 8 2 5 0
4 8 1 3 9 4

その他の回答 (1 件)

madhan ravi
madhan ravi 2019 年 5 月 12 日
C={[1 4 6 3 7 3] ;...
[4 6 2 9] ;...
[5 5 8 2 5] ;...
[4 8 1 3 9 4] };
M=max(cellfun('prodofsize',C));
Wanted = cell2mat(cellfun(@(x) [x zeros(1,M-numel(x))],C,'un',0))
  2 件のコメント
Rik
Rik 2019 年 5 月 12 日
It is unfortunate the pad function (R2016b and later) requires a cellstr input:
%doesn't work:
Wanted = cell2mat(pad(C,'right',0));
%does work:
Wanted = double(cell2mat(pad(cellfun(@char,C,'un',0),'right',char(0))));
I have the feeling Matlab is getting a bit less weakly typed than it used to be.
madhan ravi
madhan ravi 2019 年 5 月 12 日
Wow ,didn’t know that function so +1 .

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMigrate GUIDE Apps についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by