How to add a new row in matrix

2 views (last 30 days)
Tiffan
Tiffan on 4 Jun 2017
Edited: Tiffan on 6 Jun 2017
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
];

Answers (1)

Image Analyst
Image Analyst on 4 Jun 2017
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"???
  1 Comment
Tiffan
Tiffan on 5 Jun 2017
@Image Analyst, for better clarity, I've edited the question. Thanks!

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!