insert specific number of rows into matrix if condition is met and fill new cells with specific value

3 ビュー (過去 30 日間)
Hi,
I have a 2-column matrix like this:
a = [1 0; 2 0; 4 0; 8 0]
I would like to change this matrix into a matrix like this:
a_new = [1 0; 2 0; 3 NaN; 4 0; 5 NaN; 6 NaN; 7 NaN; 8 0]
i.e. matrix a with consecutive numbers in the first column and an empty cell or NaN in the added second column.
I managed to insert single rows where they should be inserted:
first_column = a(:,1);
d = diff(first_column);
f = find(d>1);
row = [0, NaN];
a = insertrows(a,row,f)
... giving me this:
a =
1 0
2 0
0 NaN
4 0
0 NaN
8 0
But I would need to insert e.g. only one row after row number 3 but three rows after row number 3.
Moreover, I want the new value of the first column to be consecutive number.
I appreciate your help a lot!!

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 11 月 25 日
In your case:
n = max(a(:,1));
out = [(1:n)',nan(n,1)];
out(a(:,1),2) = a(:,2);
  2 件のコメント
Adriana Schatton
Adriana Schatton 2019 年 11 月 25 日
Wow!! This is way more easy than the construction I had in mind!!
Thanks a lot!!
Andrei Bobrov
Andrei Bobrov 2019 年 11 月 25 日
Adriana! Please accept the answer if it helped you.

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

その他の回答 (0 件)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by