Good practice in conditional test with categorical variable
조회 수: 26 (최근 30일)
이전 댓글 표시
So I defined a categorical variable and tested its value in a conditional statement using the "==" operator, as seen in the image. The program works OK, thus I'm guessing such syntax is acceptable. But I kept getting warnings like the one in the image in the MATLAB IDE. How can my code be changed so that the warning is suppressed, and what is the underlying explanation for what is and is not a good practice when dealing with categorical variables in a conditional test?
댓글 수: 0
채택된 답변
the cyclist
2023년 3월 26일
편집: the cyclist
2023년 3월 26일
The reason you are getting this mlint warning isn't really about the categorical variables at all. It is because you are trying to make a vector comparison in the if statement.
'def' is a 1x3 character vector, so MATLAB is warning you that it is expecting an expression that will evaluate to a scalar in the if statement. It is akin to writing
if [2 3] == [5 7 11]
Now, it turns out that because MATLAB will do a conversion to compare your categorical variable to the character array
catvar = categorical({'def'},{'abc','def'});
if catvar == 'def'
fprintf("got here\n")
end
the syntax will work. (I don't know if it gives the result you intend, though.) In general, it's better not to rely on the conversion, but make it explicit. I don't know your broader context for wanting to use categorical variables overall, but this syntax would not give the warning.
catvar = categorical({'def'},{'abc','def'});
if catvar == categorical({'def'})
fprintf("got here, without mlint warning\n")
end
I do have the feeling that your whole situation might be easier if you used string arrays instead of categorical, but like I said, I don't know your broad context.
댓글 수: 6
the cyclist
2023년 3월 29일
Between @Peter Perkins and me, we probably have nearly 60 years of MATLAB experience, so if we both suggested using strings arrays, you know it's a good idea. :-)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!