Index matrix changing values outside index to NaN
1 次查看(过去 30 天)
显示 更早的评论
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]
0 个评论
采纳的回答
Voss
2021-12-14
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]'
ND = numel(data)
result = NaN(size(idx))
is_good_idx = idx <= ND
result(is_good_idx) = data(idx(is_good_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!