필터 지우기
필터 지우기

Strange bug when indexing vector

조회 수: 1 (최근 30일)
Matt Flood
Matt Flood 2021년 12월 14일
댓글: Matt Flood 2021년 12월 14일
The following piece of code works as I want it to.
It sorts the elements in a 2x2 matrix and gives equal rank order to elements with the same value.
x = [2.3333 2.3333; 2.0000 2.3333];
[y, z] = sort(x(:))
y = 4×1
2.0000 2.3333 2.3333 2.3333
z = 4×1
2 1 3 4
if any(diff(y)==0)
for n = find(diff(y')==0)+1
z(n) = z(n-1);
end
end
disp(z)
2 1 1 1
So x is sorted as [2, 2.33, 2.33, 2.33] and the elements are given the ranks [2, 1, 1, 1].
However, if I don't transpose y in the for loop, the code gives the wrong output, i.e., the rank is [2, 1, 1, 3].
x = [2.3333 2.3333; 2.0000 2.3333];
[y, z] = sort(x(:))
y = 4×1
2.0000 2.3333 2.3333 2.3333
z = 4×1
2 1 3 4
if any(diff(y)==0)
for n = find(diff(y)==0)+1
z(n) = z(n-1);
end
end
disp(z)
2 1 1 3
As far as I can tell, there is no logical reason why not transposing y vector should produce a different output.
Can someone please explain why this is happening??
  댓글 수: 2
Voss
Voss 2021년 12월 14일
편집: Voss 2021년 12월 14일
for loops in MATLAB loop over the columns of the variable you tell it. So, for example, this:
for i = [1 2 3]
display(i);
end
i = 1
i = 2
i = 3
is as expected (columns of a row vector are scalars), but the following only loops once and i is the whole column vector:
for i = [1; 2; 3]
display(i);
end
i = 3×1
1 2 3
Generalizing to a 2d matrix:
x = magic(3);
for i = x
display(i);
end
i = 3×1
8 3 4
i = 3×1
1 5 9
i = 3×1
6 7 2
So in your second example (without transposing y), n takes the value [3; 4] and the loop iterates once, rather than the loop iterating twice with n taking 3 and then 4, which is what it does in the first example.
Matt Flood
Matt Flood 2021년 12월 14일
Thank you @Benjamin
I see it now - it's treating [3;4] as a single interable as opposed to two individual ones.

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

답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by