MATLAB Answers

adding different number of columns to specific row

17 views (last 30 days)
Shayma on 30 Jan 2020
Commented: Shayma on 6 Feb 2020
I have 2 differnt csv files, i want to append the columns from book8 to book 7 based on the name column that appears in the 2 files, the name in 7 are unique but in 8 there are duplicates, so the appending columns may differ from row to another ...
is there a way to add the corresponding columns to a specific row?
i tried to append the columns in differnt ways with no success...
for row=(2:r) %


Sign in to comment.

Answers (1)

Ridwan Alam
Ridwan Alam on 30 Jan 2020
Edited: Ridwan Alam on 30 Jan 2020
Try using the table join() method:
M_obs = readtable('book7.csv');
M_pri = readtable('book8.csv');
[~,M_pri_idx] = unique(M_pri(:,1));
M_pri_new = M_pri(M_pri_idx,:);
new_table = join(M_obs,M_pri_new,'Keys',[1,1]);
Hope this helps.


Shayma on 1 Feb 2020
Thank you for answering ..
but the joining table in this case will have only one row for each entry because of the unique function, howevere what i want to add is-> if book8.csv has two rows of the entry "zinc543"
it will append these two rows as new columns for the entry "zinc543" in book7
this is how some rows will have more columns than others, depends on how many times it appears in the book8.csv file, is it possible?
Ridwan Alam
Ridwan Alam on 2 Feb 2020
Sorry, but the question is a bit confusing.
You wrote: if book8.csv has two rows of the entry "zinc543", it will append these two rows as new columns for the entry "zinc543" in book7. Can you mention which row in book 7 and book 8 has this?
Are you trying to extend the table_book_8 with columns from table_book_7 wherever available? If yes, try this code:
zSize = [size(B,1), size(B,2) + size(A,2) - 1];
zType = ["string",repmat("doublenan",[1,zSize(2)-1])];
zNew = table('Size',zSize,'VariableTypes',zType);
zVar = {B.Properties.VariableNames{:},A.Properties.VariableNames{2:end}};
zNew.Properties.VariableNames = zVar;
for i = 1:height(zNew)
zAind = find(table2array(A(:,1))==table2array(zNew(i,1)));
if ~isempty(zAind)
zNew(i,1+width(B):end) = A(zAind,2:end);
% zNew contains all of B, and adds A to wherever available
Shayma on 6 Feb 2020
sorry, I update the files, im trying to extend book7.csv with the columns from book8.csv
ZINC02619534 in row 3 at book7 will have the columns (2:end) from book8, from the rows 3,6,7
while ZINC02638599 for example will have the columns from book8 - row 13 only because it appears only once ..

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!