Effacer les filtres
Effacer les filtres

Index matrix changing values outside index to NaN

1 vue (au cours des 30 derniers jours)
Mackenzie Taylor
Mackenzie Taylor le 14 Déc 2021
Commenté : Mackenzie Taylor le 14 Déc 2021
I have an index matrix that is 480x1 in size with values ranging from 1 to 267, and I have a data matrix that is 261x1 in size. I need to multiple the two, or use the index matrix to index the data matrix resulting in a 480x1 matrix. The issue is that i cannot do so because some of the values in the index exceed the range of rows available in the data matrix (i.e., 262) and I cannot remove rows in the index exceeding the range of rows in the data matrix, because I ultimately need a resulting 480x1 data structure.
Is there a way to have a resulting 480x1 data structure where values in the index matrix that exceeded the range of rows in the data matrix are replaced by zeros or NaN?
Let's say for a simplified example I had:
Idx = [1,2,3,4,9,5,6,7] '
data = [1.5, 4.2, 3.4, 5.6, 7.8, 6.2, 7.5, 5.2]'
I'll get an error if I do result = idx(data) due to the index exceeding the dimensions of the data matrix, is there a way to get a result such as:
result = [1.5, 4.2, 3.4, 5.6, NaN, 7.8, 6.2, 7.5]

Réponse acceptée

Voss
Voss le 14 Déc 2021
idx = [1,2,3,4,9,5,6,7]'
idx = 8×1
1 2 3 4 9 5 6 7
data = [1.5, 4.2, 3.4, 5.6, 7.8, 6.2, 7.5, 5.2]'
data = 8×1
1.5000 4.2000 3.4000 5.6000 7.8000 6.2000 7.5000 5.2000
ND = numel(data)
ND = 8
result = NaN(size(idx))
result = 8×1
NaN NaN NaN NaN NaN NaN NaN NaN
is_good_idx = idx <= ND
is_good_idx = 8×1 logical array
1 1 1 1 0 1 1 1
result(is_good_idx) = data(idx(is_good_idx))
result = 8×1
1.5000 4.2000 3.4000 5.6000 NaN 7.8000 6.2000 7.5000

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by