insert row into table
132 views (last 30 days)
Show older comments
amateurintraining
on 18 Nov 2017
Commented: amateurintraining
on 20 Nov 2017
Hi. I want to make a function. This function has the input a table and a new value. How do I insert the new value into the table such that it is in order. I'm sorry if that is confusing but for example: I have a table:
a b
0 20000
120 15000
160 17000
200 19000
And I want to insert a new row where a=90. How do I do this if the provided function is already in order?
0 Comments
Accepted Answer
Walter Roberson
on 18 Nov 2017
mask = YourTable.a < 90;
newa = [YourTable.a(mask); 90; YourTable.a(~mask)];
newb = [YourTable.b(mask); NewBValue; YourTable.b(~mask)];
YourTable{:,[1 2]} = [newa, newb];
2 Comments
Walter Roberson
on 20 Nov 2017
interp_at = 90;
mask = YourTable.a < interp_at;
a_before = YourTable.a(mask);
a_after = YourTable.a(~mask);
b_before = YourTable.b(mask);
b_after = YourTable.b(~mask);
NewBvalue = interp1([a_before(end), a_after(1)], [b_before(end), b_after(end)], interp_at);
new_a = [a_before; interp_at; a_after];
new_b = [b_before; NewBValue; b_after];
YourTable{:,[1 2]} = [new_a, new_b];
However, you would probably find it much easier to adopt a modification of the technique that Akira Agata showed:
interp_at = 90;
new_a = [YourTable.a; interp_at];
new_b = interp1( YourTable.a, YourTable.b, new_a );
YourTable{:,[1 2]} = sortrows( [new_a, new_b] );
You can specify multiple locations in interp_at, as long as you make it a column vector.
More Answers (1)
Akira Agata
on 18 Nov 2017
How about concatenate 2 tables, and then sort it? Here is an example:
% Initial table
T = table(...
[0;120;160;200],...
[20000;15000;17000;19000],...
'VariableNames',{'a','b'});
% Additional data
T1 = table(90,19000,...
'VariableNames',{'a','b'});
% Concatenate and sort
Tout = [T;T1];
Tout = sortrows(Tout,'a');
The output is:
>> Tout
Tout =
5×2 table
a b
___ _____
0 20000
90 19000
120 15000
160 17000
200 19000
See Also
Categories
Find more on Graphics Object Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!