필터 지우기
필터 지우기

I want fill NaN in one column using average of two other column but I got an error.

조회 수: 2 (최근 30일)
Hey all, I want to fill all NaNs in the column named tm_m in the all tables that store in a 1 x 71 cell array named C using an average of the exact row of 2 other columns named tmax_m and tmin_m. I read the Matlab help and I thought this must work but it gave me an error:
for i=1:length(C)
if any(contains(C{i}.Properties.VariableNames,'tm_m'))
C{i}{C{i}{:,'tm_m'}=NaN, 'tm_m'} = mean([C.tmax_m(isnan(C.tm_m)), C.tmin_m(isnan(C.tm_m))],2);
end
end
the error is :
C{i}{C{i}{:,'tm_m'}=NaN, 'tm_m'} = mean([C.tmax_m(isnan(C.tm_m)), C.tmin_m(isnan(C.tm_m))],2);
Error: Incorrect use of '=' operator. To assign a value to a
variable, use '='. To compare values for equality, use '=='.
Thank you.

채택된 답변

Guillaume
Guillaume 2020년 1월 29일
The comparison operator for equality is == not =, which is exclusively for assignment.
However, you need to be aware that a NaN is never equal to anything, or greater or smaller than anything meaning that:
NaN >= NaN
NaN <= NaN
NaN == NaN
are always false.
The proper way to check for NaN is with isnan.
Overall, I'd write your code as this:
for cidx = 1:numel(C)
if ismember('tm_m', C{cidx}.Properties.VariableNames)
toreplace = isnan(C{cidx}.tm_m);
C{cidx}.tm_m(toreplace) = mean(C{cidx}{toreplace, {'tmax_m', tmin_m}});
end
end
Assuming I've undestood your code correctly. In your snippet C appears to be first a cell array of tables, then a structure.
  댓글 수: 3
Guillaume
Guillaume 2020년 1월 29일
Oops, forgot to tell mean to operate along the correct dimension (and made a typo as well, but it sounds like you corrected that). Correct code:
for cidx = 1:numel(C)
if ismember('tm_m', C{cidx}.Properties.VariableNames)
toreplace = isnan(C{cidx}.tm_m);
C{cidx}.tm_m(toreplace) = mean(C{cidx}{toreplace, {'tmax_m', 'tmin_m'}}, 2);
end
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by