insert row into table
109 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
amateurintraining
le 18 Nov 2017
Commenté : amateurintraining
le 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 commentaires
Réponse acceptée
Walter Roberson
le 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 commentaires
Walter Roberson
le 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.
Plus de réponses (1)
Akira Agata
le 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
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!