Why is NaN inserted in wrong position?
1 次查看(过去 30 天)
显示 更早的评论
I have a matrix
b = [1 3 0;-2 -1 5]
b =
1 3 0
-2 -1 5
When I perform the following operation
b(b(:,3)==5) = NaN;
the NaN is placed a the postion of -2. How come?
1 个评论
Dyuman Joshi
2023-8-17
编辑:Dyuman Joshi
2023-8-17
"the NaN is placed a the postion of -2. How come?"
Are you sure about that? The output from the code says otherwise -
b = [1 3 0;-2 -1 5];
b(b(1,:)==5) = NaN
No element in the 1st row of b equals to 5, so no assignment will take place.
采纳的回答
Star Strider
2023-8-17
It should not do anything, because 5 is in row 2, not row 1.
That aside, you need to index into ‘b’ correctly to get the desired result —
b = [1 3 0;-2 -1 5]
Check = b(1,:)==5 % Test Row #1
Check = b(2,:)==5 % Test Row #2
b(2,b(2,:)==5) = NaN % Use The Correct Indexing, Specifying The Correct Rows As Well As The Correct Columns
.
3 个评论
dpb
2023-8-17
编辑:dpb
2023-8-17
To amplify, you wrote the LHS index as single value for a 2D array which is linear addressing on the assignment but did the search on 2D expression b(:,3) which returns a 1D (column) vector. The five was in the second row so that logical vector is [0;1] or the result of find() would return the numerical index of '2' which is the correct index into that vector.
Hence, when you wrote b(.)=nan; for the assignment, the "." placeholder was the logical vector [0;1] which is the second element in the array with linear indexing and since MATLAB is column-major storage order, that is position b(1,2) in the 2D array. Ergo, the NaN showed up where the -2 was originally, just like you asked it to! :) Of course, that wasn't what you meant, but MATLAB doesn't know that...
The correct syntax is that you must use the same addressing expression on the LHS as in the RHS to make the two positions commensurate in the portion of the array they refer to; in this case repeating the reference explicitly to column 3.
Star Strider
2023-8-17
@Sam —
‘The goal is to replace any entry in and only in the third column that is equal to 5.’
Change the conditon statement to specify the third column, similar to the previous example —
b = [1 3 0;-2 -1 5]
b(b(:,3)==5, 3) = NaN
This is essentially the same as the original example, however specifying the third column.
To expand on this idea —
b = [1 3 0;-2 -1 5;7 4 6;5 9 5;2 5 8]
b(b(:,3)==5, 3) = NaN
So it replaces only the ‘5’ values in the third column, leaving all others unchanged.
.
更多回答(1 个)
Les Beckham
2023-8-17
b = [1 3 0;-2 -1 5];
b(b(:,3)==5,3) = NaN % add ,3 to select only the third column for assignment
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!