フィルターのクリア

How to conditionally change values in a table

41 ビュー (過去 30 日間)
012786534
012786534 2020 年 1 月 21 日
コメント済み: Star Strider 2020 年 1 月 21 日
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]}
  2 件のコメント
012786534
012786534 2020 年 1 月 21 日
Neat. Thank you.
Star Strider
Star Strider 2020 年 1 月 21 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by