"find" yields different results for linear vs 2D indexing
1 次查看(过去 30 天)
显示 更早的评论
Hi all. I have 2 2D matrices, and I want to find entries in 1 of these matrices that fulfill certain numerical criteria and put these into a different matrix containing those found entries and only 0 everywhere else. The straightforward way to do this is with the "find" function:
idx = find((t_total > 0) & (t_total < 1) & (s_total >= 0) & (s_total <= 1));
t_hit = zeros(size(t_total));
t_hit(idx) = t_total(idx);
Another idea I had was to use rows and columns, since that might come in handy later, i.e.:
[rows,columns] = find((t_total > 0) & (t_total < 1) & (s_total >= 0) & (s_total <= 1));
t_hit = zeros(size(t_total));
t_hit(rows,columns) = t_total(rows,columns);
Surprisingly though (at least to me), these do not yield the same results and I do not understand why. I checked the maximum value of t_hit and in the former case, as expected, I got values in the range of 0 to 1 (i.e. the range I restricted the indices to in "find"). In the latter case, however, I get values significantly outside of this range. Why?
0 个评论
采纳的回答
Steven Lord
2022-8-24
You don't need to use find. You don't care where the elements that satisfy your criteria are located, all you care about is that you can address those elements. For this you can use logical indexing.
A = magic(4)
mask = (6 < A) & (A < 13)
B = zeros(size(A));
B(mask) = A(mask).^2
You could create the equivalent of B using linear indices:
inds = find(mask)
C = zeros(size(A));
C(inds) = A(inds).^2
isequal(B, C) % true
But this involves an extra call to the find function that is not necessary.
3 个评论
Cris LaPierre
2022-8-24
You can still find the (rows, columns) if that is information you need elsewhere. Just use sub2ind to turn them into a linear index for extracting/assigning.
更多回答(1 个)
Cris LaPierre
2022-8-24
编辑:Cris LaPierre
2022-8-24
For what I believe is your desired outcome, you need to use linear indexing (your first code).
The reason is because t_total(rows,columns) does not extract individual values from your variable. It extracts all values is all (row,column) pairs. For example
b=rand(5)
% This extracts a 3x3 matrix, not 3 individual numbers
b([1 3 4],[2 4 5])
The same thing happens when making the assigment. The (row,column) indices do not represent individual elements, but instead a matrix of every row and column combination.
a=zeros(5);
a([1 3 4],[2 4 5])=b([1 3 4],[2 4 5])
The way to assign to individual elements is to use linear indexing.
idx = sub2ind(size(b),[1 3 4],[2 4 5]);
b(idx)
c=zeros(size(b));
c(idx) = b(idx)
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!