Repeat previous row if condition
显示 更早的评论
Hi, I have an nx2 matrix, the first column gives the order, 10 20 30 40 and then repeats again, but if there is no observation it jumps to the next (eg if no 40 then it has 10 20 30 10 20 30 40 ....)
What I need is to repeat what is in the previous row in the case where there is no last (40) or next to last (30):
A) If there is no 40 but there is 30, then create row 40 and repeat element of 30 in the second column.
B) If there is no 40 and no 30 but there is 20, then create row 30 and 40 and repeat element of 20 in the second column.
C) If there is no 30 but there is 20, then creaste row 30 and repeat element of 20 in the second column.
I give an example with matrix M1 below for the 3 cases above.
Original matrix M1 is 12x2
M1 = [
10 44;
20 72;
30 21;
40 13;
10 32;
20 26;
30 55;
10 23;
20 98;
10 36;
20 84;
40 22]
New matrix M2 is 16x2
M2 = [
10 44;
20 72;
30 21;
40 13;
10 32;
20 26;
30 55;
40 55;
10 23;
20 98;
30 98;
40 98;
10 36;
20 84;
30 84;
40 22]
In M2 since the first cycle 10 20 30 40 in M1 was ok no additions.
But the second cycle in M1 has no 40, so M2 creates the row 40 and repeats element of 30.
The third cycle has no 30 nor 40, but has 20, so creates 30 and 40 and repeats element of 20.
The fourth cycle has no 30 so creates 30 and repeats element of 20 (note 40 is not touched)
Help please
采纳的回答
更多回答(1 个)
dpb
2015-2-18
I've no magic bullet but
>> idx=find((diff([0; M(:,1)])>0 & diff([0; M(:,1)])~=10) | ...
(diff([0; M(:,1)])<0 & diff([0; M(:,1)])~=-30) )
ans =
8
10
12
Gives you the indices in the vector of the locations missing one or more values. Best I got is to then walk thru this array and check the difference between that location and the prior and use that to control the arguments to a repmat call.
One thing you can do is to build a new M array a priori that is clean for all the first column(*) and as you're working thru the existing vector that's the target for the new rows, meanwhile you copy those that aren't missing as you go until get to next element in the above list.
Bound to be a way accumarray could help but I've got other commitments that prevent spending more time at the moment, sorry...
(*) i.e., if the 10 is always present, then the new array could be built as
nReps=sum(M(:,1)==10); % how many groups are there?
N=zeros(nReps,2); % a new full-length array
N(:,1)=repmat([10:10:40].',nReps,1); % fill the first column
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!