How to add a new row in matrix
3 次查看(过去 30 天)
显示 更早的评论
A = [
1 3 270 395
1 2 1590 1650
1 5 1650 1710
2 3 260 310
2 2 1550 1600
2 7 1600 1650
2 1 1650 1700
3 3 245 405
3 1 405 510
3 7 1025 1075
3 3 1075 1340
3 3 1340 1685
4 3 240 380
4 5 1610 1650
4 2 1650 1680
];
For every unique ID (first column in matrix A), the following procedure should be followed:
The max value in the forth column should be identified. If it is greater than 1680, then we need to adjust the matrix. First, the max value in the matrix should be replaced by 1680. Second, a new row should be added to matrix (at first row) and for its values: 2_1: the ID (first column) should be repeated as current ID, 2_2: the second column value should be repeated as second column value for identified max value, 2_3: the third column value should be 240, 2_4: the forth column value should be same as value in the third column (first row before adjusting the matrix).
e.g. for ID = 1:
Input:
1 3 270 395
1 2 1590 1650
1 5 1650 1710
Output (after applying steps):
1 3 240 270
1 3 270 395
1 2 1590 1650
1 5 1650 1680
Output matrix for all IDs:
out = [
1 3 240 270
1 3 270 395
1 2 1590 1650
1 5 1650 1680
2 3 240 260
2 3 260 310
2 2 1550 1600
2 7 1600 1650
2 1 1650 1680
3 3 240 245
3 3 245 405
3 1 405 510
3 7 1025 1075
3 3 1075 1340
3 3 1340 1680
4 3 240 380
4 5 1610 1650
4 2 1650 1680
];
0 个评论
回答(1 个)
Image Analyst
2017-6-4
I don't understand your complicated rules. I got as far as determining the max for each group (the ID # in col 1) and then subtracting 1680 from it. This code will do that:
groupMaxes = grpstats(A(:, 5), A(:, 1), 'max')
groupDeltas = groupMaxes - 1680
You get
groupMaxes =
1710
1700
1685
1680
groupDeltas =
30
20
5
0
but I have no idea what to do after that because the explanation and example result are so confusing (to me). I mean you say "one new column should be added" then you say "The second column value should be repeated for the new added row." _What* column value should be repeated? What new added row? Did you say to add a row?
And I don't understand what you mean when you say "the fifth column ended" or "the third row is ended". What does it mean for a row or column to be "ended"???
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!