Strange bug when indexing vector
1 次查看(过去 30 天)
显示 更早的评论
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(:))
if any(diff(y)==0)
for n = find(diff(y')==0)+1
z(n) = z(n-1);
end
end
disp(z)
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(:))
if any(diff(y)==0)
for n = find(diff(y)==0)+1
z(n) = z(n-1);
end
end
disp(z)
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
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
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
Generalizing to a 2d matrix:
x = magic(3);
for i = x
display(i);
end
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.
回答(0 个)
另请参阅
类别
在 Help Center 和 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!