Unexpected Matlab edge case behavior
이전 댓글 표시
I recently stumbled upon an edge case in Matlab where indexing doesn't always work as expected (See answers below). What edges cases are are you aware of in Matlab where the behavior at the edge case is not as expected? An example of an expected edge case (i.e. not an answer) would be taking the mean of a set of numbers that happens to include a NaN value. Since this might not normally happen, it might be considered an edge case, but its answer is certainly expected.
This is somewhat related to:
but with the lack of focus on values that have "special" meaning.
채택된 답변
추가 답변 (5개)
sum(x)
This operates along the first non-singelton dimension. This is useful for short hacks in the command window, documented, well known, but it is still a pitfall, when the input is a row vector unexpectedly. Therefore specifying the dimension for sum, mean, std, max etc. is obligatory for reliable code.
Btw. sum(x) has been 20% faster than sum(x, 1) in older Matlab releases. But the necessary testing by if size(x, 1) > 1, ... reduced this benefit.
댓글 수: 1
Sean de Wolski
2013년 10월 8일
I'd say this is necessary for many functions:
mean, std, min, max, diff, %etc.
Jan
2013년 10월 8일
sum(X, 2) % Operate along the 2nd dimension
mean(X, 2) % Operate along the 2nd dimension
max(X, 2) % *Not* along the 2nd dimension, but the max of X and the value 2
std(X, 1); % *Not* along the 1st dimension
max(X, [], 2) % along the 2nd dimension
std(X, 0, 1) % along 1st dimension
Jan
2013년 10월 8일
1 개 추천
acos(x) replies complex values, when the input is greater than 1.0 due to rounding errors. So either test abs(x) - 1 < 100*eps or a similar arbitrary limit, or use real(acos(x))
Jan
2013년 10월 8일
The non-functional form of commands is super edgy and the behavior changes with the Matlab versions:
fullfile * * % ok in Matlab 2009a, same as: fullfile('*', '*');
fullfile * p % fails in Matlab 2009a: '*' is assumed to be a multiplication
Both worked in older Matlab version and might work in 2013a again. There are many examples where numbers, operators and characters are treated differently depending on the command and the Matlab version.
While I use the non-functional form of commands in the command window, I avoid this strictly inside code, even for hold('on') to be consequent.
Jim Hokanson
2013년 10월 10일
댓글 수: 1
Jan
2013년 10월 10일
The trailing singelton dimensions vanish magically, such that ndims and size reply correct by unexpected results. Inside a MEX function you can create trailing singleton dimensions, which are not cleaned, when an array is provided as output.
Some functions accept and access of virtual trailing dimensions, some reject if the "dims" input is beyond ndims. I cannot test this currently, but try sum and filter.
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!