필터 지우기
필터 지우기

Loop through multiple columns in table using if condition

조회 수: 5 (최근 30일)
YaaW
YaaW 2023년 1월 6일
댓글: YaaW 2023년 1월 6일
I have a large table, let's call it X, with many rows and columns. I want to loop through 10 columns (named X.A, X.B, X.C, etc.), and when all of the 10 columns for a specific row have the value NaN, I want a 0 in the column X.result, and when at least one or more of the columns has a value (an integer), I want it to return a 1 in the column X.result.
I tried to create this with looping through 1 column first and add more after, but I can't seem to manage it to work:
for i = 1:length(X.result)
if (~isnan((X.A)))
X.result(i) = 1;
end
end
I think I might be doing something wrong in defining variables but I can't seem to figure it out. The first line after the if statement ( if (~isnan((X.A))) ) works, but no 0 or 1 is assigned to the X.result column. Can anybody help me with this? Thanks!

채택된 답변

VBBV
VBBV 2023년 1월 6일
X.A = [randi([0 10],1,7) NaN]
X = struct with fields:
A: [2 10 7 7 3 4 8 NaN]
X.B = repmat(NaN,1,8);
for i = 1:length(X.A)
if (isnan(X.A(i)) & isnan(X.B(i)))
X.result(i) = 0;
elseif ~isnan(X.A(i)) | ~isnan(X.B(i))
X.result(i) = 1;
end
end
[X.A.', X.B.', X.result.']
ans = 8×3
2 NaN 1 10 NaN 1 7 NaN 1 7 NaN 1 3 NaN 1 4 NaN 1 8 NaN 1 NaN NaN 0
  댓글 수: 2
VBBV
VBBV 2023년 1월 6일
extend the condition /check you have inside the loop, upto 10 columns as
if (isnan(X.A(i)) & isnan(X.B(i))) & isnan(X.C(i)) ... so on
YaaW
YaaW 2023년 1월 6일
Thanks! Keep forgetting to put the (i) behind the variable :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by