1

How to obtain matrix Md from matrix M matching next conditions:

if M is:

M=[0.000000 1188.000000 340.216815
0.000000    1186.437500 570.718050
0.000000    1183.312500 769.256473
6.500000    1188.500000 331.115127
6.500000    1186.963013 510.419428
6.500000    1183.889160 719.346166
13.000000   1189.000000 325.858265
13.000000   1187.488647 426.599681
13.000000   1184.465942 671.896040
19.500000   1189.000000 330.567837
19.500000   1187.529785 383.856624
19.500000   1184.589478 643.279493
26.000000   1190.000000 333.606362
26.000000   1188.539795 381.784469
26.000000   1185.619263 648.680568];

Find the maximum value of M(:,2) where M(:,1) is equal to (0, 6.5.. 26) this is:

for i=0:6.5:26
ind = M(:,1) == i;
max(M(ind,2))
end

obtaining

ans = 1188
ans = 1188.5
ans = 1189
ans = 1189
ans = 1190

The idea is to use these maximun values in order to substract them to from other values in M(:,2) where M(:,1) is equal to (0, 6.5.. 26). For example: the max value in M(:,2) where M(:,1)=0 is 1188, then we would substract from 1188: 1188, 1186.437500 and 1183.312500, which are the values of the M(:,2) column matching M(:,1)=0.

1188-1188 = 0.0000
1188-1186.437500 = 1.5625
1188-1183.312500 = 4.6875

Then do the same for 6.5, 13..26. The Result would be:

Md=[0.000000    0.0000  340.216815
0.000000    1.5625  570.718050
0.000000    4.6875  769.256473
6.500000    0.0000  331.115127
6.500000    1.5370  510.419428
6.500000    4.6108  719.346166
13.000000   0.0000  325.858265
13.000000   1.5114  426.599681
13.000000   4.5341  671.896040
19.500000   0.0000  330.567837
19.500000   1.4702  383.856624
19.500000   4.4105  643.279493
26.000000   0.0000  333.606362
26.000000   1.4602  381.784469
26.000000   4.3807  648.680568];
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Adolf
  • 17
  • 6

2 Answers2

1

You are almost there:

for i=0:6.5:26
   ind = M(:,1) == i;
   m = max(M(ind,2));
   M(ind,2) = m - M(ind,2);
end

I just added one line to the code in the question. This line does as you specify: subtract the values in the second column for rows ind from their max, and assign it back into those cells.

Here we are modifying M instead of creating a new matrix Md, this can be fixed by starting with a copy of the matrix.

There might ways to do this that do no use a loop, but unless this turns out to be a bottleneck in your code, keep it simple and readable!

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
0

A solution can be using grouping the first column to compute max for each group:

maxs = accumarray(M(:,1), M(:,2), [], @max);

Also, as the comparison of two float numbers with == can be erroneous it would better use this method.

OmG
  • 18,337
  • 10
  • 57
  • 90