How to duplicate certain rows of a dataset (class = dataset)?

2 次查看(过去 30 天)
I have a dataset with 200 rows and 20 columns. I want to duplicate each row that has a depth value of 10, e.g. dataset.depth == 10, and place the duplicate row in the next row. (The reason for duplication is because I will change values in 2 of the columns of this duplicated row, but most of the column values will remain the same.) I am thinking that a for loop with an if/else statement could work.
for i=1:length(dataset.depth)
if dataset.depth(i) == 10
DUPLICATE COMMAND HERE NEEDED
end
end
Thanks!
  2 个评论
José-Luis
José-Luis 2012-10-17
编辑:José-Luis 2012-10-18
I don't really understand how your data is organized. As I understand it, you have an array of structures and one of the fields is depth. In that case what do you mean by repeating rows? Or is the depth one of the columns in your matrix?
George McFadden
George McFadden 2012-10-23
Jose-Luis, I am using a dataset array, so not a structure. Thanks for your interest, I ended up using the following code:
for i=1:286
if aa.depth(i) == 10
aa = [aa;aa(i,:)];
aa=sortrows(aa,{'dpID','depth'});
aa(i+1,7) = dataset(0);
aa(i+1,12) = dataset(x);
i = i + 1;
end
end
Straight forward code, the important lines being aa = [aa;aa(i,:)]; which duplicates the line at i and appends to end of list; and the other important line being i = i +1, this avoids the loop duplicating the same row infinitely.
Thanks!

请先登录,再进行评论。

回答(2 个)

Matt J
Matt J 2012-10-17
编辑:Matt J 2012-10-17
No need to use for-loops at all:
B=num2cell(A,2).'; %A is 200x20
B=[B;B];
B(2,dataset.depth~=10)={[]};
newmatrix = vertcat(B{:});

Peter Perkins
Peter Perkins 2012-10-23
As Matt says, no need to use loops. This might be a little simpler.
First cook up some data:
aa = dataset((1:100)',randi(10,100,1),randn(100,1),'VarNames',{'dpID' 'depth' 'somethingElse'});
Then find the rows to duplicate, and put duplicates at the end:
i = (aa.depth == 10);
Then sort to put duplicates in place:
aa = sortrows([aa; aa(i,:)],'dpID');
Hope this helps.

类别

Help CenterFile Exchange 中查找有关 Data Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by