"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!