How to conditionally change values in a table

39 次查看(过去 30 天)
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,

采纳的回答

Star Strider
Star Strider 2020-1-21
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]}

更多回答(1 个)

woahs
woahs 2020-1-21
编辑:woahs 2020-1-21
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;

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by