MATLAB Answers

Insert new row with values in a table before specific values

조회 수: 5(최근 30일)
Lukas Netzer
Lukas Netzer 2021년 8월 9일
답변: Peter Perkins 2021년 8월 9일
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!

채택된 답변

Yazan
Yazan 2021년 8월 9일
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

추가 답변(1개)

Peter Perkins
Peter Perkins 2021년 8월 9일
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

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by