Clear Filters
Clear Filters

How to include a vector into a table and duplicate the remaing rows (see picture)

6 views (last 30 days)
Hi everbody,
I don't really know how to go about mering my data.
On the on hand I have got an table 3570 x 20 and on the other hand a matrix 3570 x 240. Additional I have a true and false matrix which corresponds to the value matrix. Finaly I want to merge the matrix into table like in the picture. The other coloums of the table should simply be duplicated.
I would be very happy about an answer. Many thanks in advance.
Best Marco

Accepted Answer

Marco Schnizer
Marco Schnizer on 2 Feb 2022
I finally came up with the following solution:
% Transpose, so every unit is a coloum
valueMatrix = valueMatrix'
tfMatrix = tfMatrix'
RepeatsPerRow = sum(tfMatrix) % total rows per unit
RowsTot = sum(RepeatsPerRow) % total rows of final table
% Expand the specific matrices to total number of rows
var1 = repelem(ProductName,RepeatsPerRow);
var2 = repelem(NoTubeRows,RepeatsPerRow);
% ...
% Reshape value matrix to one coloum
valueMatrix = reshape(valueMatrix,[],1)
tfMatrix = reshape(tfMatrix ,[],1)
% final value matrix with indexing
valueMatrixFinal = valueMatrix(tfMatrix)
% create the table
Table = table(var1, valueMatrixFinal, var2)
I think my problem descripton wasn't detailed enough. But thanks to Simon for the inspiration!
Maybe not the fastest but for me a understandable solution.

More Answers (1)

Simon Chan
Simon Chan on 2 Feb 2022
Suppose your value matrix and true/false matrix is variable "data" and "index" respectively.
And the biggest table is T, with size 3570 x 240.
Then you may try the following:
data_transpose = transpose(data);
data_table = data_transpose(index');
num_row = sum(index,2); % Total number of rows in the final table
Ny = 3570; % Original row number = 3570
B = arrayfun(@(r,s) varfun(@(x) repelem(x(s,:),r,1),T),num_row,(1:Ny)','uni',0); % Duplicate the rows
T1 = cat(1,B{:}); % Combine the small tables
% Suppose you would like to insert the new column in column #6
T2 = [T1(:,1:5),table(data_table), T1(:,6:240)];

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!