How to conditionally change values in a table
29 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
012786534
il 21 Gen 2020
Commentato: Star Strider
il 21 Gen 2020
Hi,
I am wondering to conditionally change values in a table. In the table below, everytime that t.val2 is 3 or 4, I want t.val1 to become NaN. How would I do that ?
val1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}.';
val2 = {1, 3, 2, 1, 1, 4, 1, 1, 3}.';
t1 = table(val1, val2);
Thank you,
0 Commenti
Risposta accettata
Star Strider
il 21 Gen 2020
Try this:
val1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}.';
val2 = {1, 3, 2, 1, 1, 4, 1, 1, 3}.';
t1 = table(val1, val2);
lidx = ([t1.val2{:}] == 3) | ([t1.val2{:}] == 4);
t1.val1(lidx) = {NaN}
producing:
t1 =
9×2 table
val1 val2
_______________ _______________
{[1.0000e+000]} {[1.0000e+000]}
{[ NaN]} {[3.0000e+000]}
{[3.0000e+000]} {[2.0000e+000]}
{[4.0000e+000]} {[1.0000e+000]}
{[5.0000e+000]} {[1.0000e+000]}
{[ NaN]} {[4.0000e+000]}
{[7.0000e+000]} {[1.0000e+000]}
{[8.0000e+000]} {[1.0000e+000]}
{[ NaN]} {[3.0000e+000]}
2 Commenti
Più risposte (1)
woahs
il 21 Gen 2020
Modificato: woahs
il 21 Gen 2020
First off, unless you have a particular reason for keeping your values in cell arrays, I'd suggest converting them into just double arrays. After that, you can just use ismember to find where an array contains a value of a set you can specify (e.g. 3, 4 in below example) and set those indices to nan.
t1 = cell2table([val1, val2], 'VariableNames', {'val1', 'val2'});
t1.val1(ismember(t1.val1, [3, 4])) = nan;
0 Commenti
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!