"find" yields different results for linear vs 2D indexing
Mostra commenti meno recenti
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?
Risposta accettata
Più risposte (1)
Cris LaPierre
il 24 Ago 2022
Modificato: Cris LaPierre
il 24 Ago 2022
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)
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!