フィルターのクリア

Index matrix changing values outside index to NaN

1 回表示 (過去 30 日間)
Mackenzie Taylor
Mackenzie Taylor 2021 年 12 月 14 日
コメント済み: Mackenzie Taylor 2021 年 12 月 14 日
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]

採用された回答

Voss
Voss 2021 年 12 月 14 日
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
  1 件のコメント
Mackenzie Taylor
Mackenzie Taylor 2021 年 12 月 14 日
Thank you so much! This works.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by