How to insert data to a matrix based on index values stored in a matrix?

9 ビュー (過去 30 日間)
Martti Ilvesmäki
Martti Ilvesmäki 2021 年 6 月 16 日
コメント済み: Martti Ilvesmäki 2021 年 6 月 17 日
Hello!
I am a beginner in Matlab and would like to ask a question regarding inserting NaN- values to a matrix according to index values that are stored in a matrix.
I have the following case:
a is a matrix containing data I want to insert NaN- values to the start and end of the vector.
a = vector 250x111
b is a matrix where first row has index values of the start cut-off point and second row information of end cut-off point. For example start cut-off point could be 20 and end cut-off point 105 for a certain data point.
b = matrix 2x111
I believe I can implement this with following by using for- loop through data (example for the first data point):
a( 1:b(1,1) ) = NaN;
a( b(2,1):end) = NaN;
However, I am wondering if there is a way or function to conduct this smoothly? I have noticed while reading this forum that there is usually more efficient ways than using for- loops to conduct this kind of operations and there for wanted to ask for tips.
Thank you already in advance!
  2 件のコメント
Stephen23
Stephen23 2021 年 6 月 16 日
As you have just one vector, surely this is just:
a(1:max(b(1,:))) = NaN;
a(min(b(2,:)):end) = NaN;
(note that in your example you have swapped the row and column indexing).
Martti Ilvesmäki
Martti Ilvesmäki 2021 年 6 月 16 日
編集済み: Martti Ilvesmäki 2021 年 6 月 17 日
Thank you for the answer, and true that my example indexing was indeed accidentally swapped.
I just realized I wrote incorrectly description of vector a. It is actually a matrix containing 111 vectors of length 250.
a = matrix 250x111
b contains cut-off positions for start and end for each vector as described in the original message.
I have edited the post accordingly now.

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

採用された回答

Stephen23
Stephen23 2021 年 6 月 17 日
編集済み: Stephen23 2021 年 6 月 17 日
a = randi(9,7,5)
a = 7×5
8 9 6 7 6 4 7 9 8 3 8 9 4 1 3 7 8 5 6 8 9 6 3 3 9 3 2 4 4 6 7 8 3 3 8
b = [2,2,3,1,2;6,5,7,6,5]
b = 2×5
2 2 3 1 2 6 5 7 6 5
rwv = 1:size(a,1);
idx = rwv(:)<=b(1,:) | rwv(:)>=b(2,:);
a(idx) = NaN
a = 7×5
NaN NaN NaN NaN NaN NaN NaN NaN 8 NaN 8 9 NaN 1 3 7 8 5 6 8 9 NaN 3 3 NaN NaN NaN 4 NaN NaN NaN NaN NaN NaN NaN
If you are using a MATLAB version prior to R2016b replace both of the logical comparisons with BSXFUN and function handles to the same logical functions.
  1 件のコメント
Martti Ilvesmäki
Martti Ilvesmäki 2021 年 6 月 17 日
Thank you, this worked very well and answered my question!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by