2

It's very convenient if it was possible to use colon operator on a expression. Well to my knowledge, it's not possible. For example when I want to calculate the differences between two matrices, I have to do it in two lines.

diff = (a - b);
err = sum(abs(diff(:)));

instead of

diff = sum(abs((a-b)(:)));

Is there anyway around it?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Mohammad Moghimi
  • 4,636
  • 14
  • 50
  • 76

3 Answers3

3

Two options:

err = sum(abs(a(:)-b(:)));

or

err = sum(abs(reshape(a-b,[],1)));
Ramashalanka
  • 8,564
  • 1
  • 35
  • 46
3

You can get around syntax limitations with anonymous helper functions. EG

oneD = @(x)x(:);
diff = sum(abs(oneD(a-b))));

Still takes two lines though.

Pursuit
  • 12,285
  • 1
  • 25
  • 41
  • I like your idea. I wish you could name oneD colon. It might conflict with the colon operator! – Mohammad Moghimi Feb 18 '12 at 09:22
  • You are right. Using the name `colon` would cause you no end of trouble. – Pursuit Feb 18 '12 at 15:14
  • 1
    So you consider it a valid answer to replace a two-line solution with another two-line solution, and in addition replace the simple colon operator with an anonymous solution! "Things should be made as simple as possible, but not any simpler." – Kavka Feb 19 '12 at 04:27
1

In this particular case, you could do sum(abs(a(:)-b(:))), but in general Matlab doesn't support that sort of nested indices.

mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194