How to conditionally change values in a table
30 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
012786534
am 21 Jan. 2020
Kommentiert: Star Strider
am 21 Jan. 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 Kommentare
Akzeptierte Antwort
Star Strider
am 21 Jan. 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 Kommentare
Weitere Antworten (1)
woahs
am 21 Jan. 2020
Bearbeitet: woahs
am 21 Jan. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!