How to conditionally change values in a table

조회 수: 42 (최근 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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by