Insert new row with values in a table before specific values

27 Ansichten (letzte 30 Tage)
Hey,
I have a table with 3 columns containing the following values:
Now I want to insert a new row with (0,0,0) everytime WP1 hits 0 before that, so that the new table looks like that:
What is an efficient way to do that?
Thanks for your help!

Akzeptierte Antwort

Yazan
Yazan am 9 Aug. 2021
WP1 = [0 145 169 1693 1708 2729 0 48];
WP2 = [145 169 1693 1708 2729 2779 48 1382];
WC = [0 1 1 1 1 0 0 1];
dat = [WP1', WP2', WC'];
T = table(WP1', WP2', WC', 'VariableNames', {'WP1', 'WP2', 'WC'});
disp(T)
WP1 WP2 WC ____ ____ __ 0 145 0 145 169 1 169 1693 1 1693 1708 1 1708 2729 1 2729 2779 0 0 48 0 48 1382 1
idx = find(T.WP1 == 0);
idx = idx + (0:length(idx)-1)';
Idx = true(size(WP1') + [length(idx) 0]);
Idx(idx) = false;
dat2 = zeros(size(dat) + [length(idx), 0]);
dat2(Idx, :) = dat;
T2 = table(dat2(:,1), dat2(:,2), dat2(:,3), 'VariableNames', {'WP1', 'WP2', 'WC'});
disp(T2)
WP1 WP2 WC ____ ____ __ 0 0 0 0 145 0 145 169 1 169 1693 1 1693 1708 1 1708 2729 1 2729 2779 0 0 0 0 0 48 0 48 1382 1

Weitere Antworten (1)

Peter Perkins
Peter Perkins am 9 Aug. 2021
It is possible to just use tabular subscripting to insert these rows. This is kind of old school MATLAB. Don't know if it is easier or harder to understand.
>> WP1 = [0; 145; 169; 1693; 1708; 2729; 0; 48];
>> WP2 = [145; 169; 1693; 1708; 2729; 2779; 48; 1382];
>> WC = [0; 1; 1; 1; 1; 0; 0; 1];
>> T = table(WP1, WP2, WC)
T =
8×3 table
WP1 WP2 WC
____ ____ __
0 145 0
145 169 1
169 1693 1
1693 1708 1
1708 2729 1
2729 2779 0
0 48 0
48 1382 1
Create an index vector that puts existing rows at their new locations.
>> n = height(T);
>> i = (1:n)';
>> incr = zeros(size(i));
>> incr(j) = 1;
>> i2 = i + cumsum(incr)
i2 =
2
3
4
5
6
8
10
11
Create an index vector that puts the inserted rows at their new locations.
>> j = find(T.WC == 0);
>> incr = ones(size(j)); incr(1) = 0;
>> j2 = j + cumsum(incr)
j2 =
1
7
9
Add a row at the end, merge the index vectors, and use that to insert copies of the new end row into the right places.
>> T{end+1,:} = [0 0 0];
>> [~,k] = sort([i2; j2]);
>> k(j2) = n+1;
>> T = T(k,:)
T =
11×3 table
WP1 WP2 WC
____ ____ __
0 0 0
0 145 0
145 169 1
169 1693 1
1693 1708 1
1708 2729 1
0 0 0
2729 2779 0
0 0 0
0 48 0
48 1382 1

Kategorien

Mehr zu Data Type Identification finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by