Add rows to table

조회 수: 19 (최근 30일)
SilverSurfer
SilverSurfer 2020년 7월 17일
댓글: SilverSurfer 2020년 7월 19일
I need to concatenate horizzontaly two tables.
If tables does not have same rows it is not possibile to use horzcat so my idea was to adjust tables row in order to use horzcat.
Each column will contain strings but can have different number of rows so some of them shall remain empty.
I'm currently using this piece of code on 2020a and it works. Now I'm porting to 2018b but it does not work.
% create empty table
filedata = table.empty;
for z = 1 : sheets_nr
sheetData = readtable(filename,'Sheet',cell2mat(sheets(z)));
[n1,~] = size(sheetData);
[n2,~] = size(filedata);
if n1 > n2
filedata(n2+1:n1,:) = {''} ;
else
sheetData(n1+1:n2,:) = {''} ;
end
% concatenate horizzontally
filedata = horzcat(filedata, sheetData);
end
The error is related to
filedata(n2+1:n1,:) = {''} ;
First error is "conversion from double from cell is not possible".
Even if I remove curly brackets I get another error "To assign to or to create a variable in a table, the number of rows must match the height of the table"
I just want to increase the number of rows and fill them with empty string.

채택된 답변

madhan ravi
madhan ravi 2020년 7월 17일
s = [1, 2, 3;...
4, 5, 6]; % an example
T = array2table(s);
T1 = array2table(repmat("",2,3));
T1.Properties.VariableNames = T.Properties.VariableNames
[T; T1]
  댓글 수: 1
SilverSurfer
SilverSurfer 2020년 7월 19일
Thank you. It was I great suggestion. I modified existing code and now it is working also on 2018b
% create empty table
filedata = table.empty;
for z = 1 : sheets_nr
sheetData = readtable(filename,'Sheet',cell2mat(sheets(z)));
[n1,~] = size(sheetData);
[n2,~] = size(filedata);
if n1 > n2
delta = n1-n2
[rows,columns] = size(filedata);
if rows == 0
% in the first iteration fill only one column with ""
filedata = array2table(rempat("",delta,1));
else
% create a table with additional rows to add and the same number of columns
new_rows = array2table(rempat("",delta,colonne));
% assign the same variable names of existing table
new_rows.Properties.VariableNames = filedata.Properties.VariableNames
% concatenate vertically
filedata = vertcat(filedata,new_rows)
end
else
...
end
% concatenate horizzontally
filedata = horzcat(filedata, sheetData);
end

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

추가 답변 (0개)

카테고리

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