2
votes

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?

3

3 Answers

3
votes

Two options:

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

or

err = sum(abs(reshape(a-b,[],1)));
3
votes

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.

1
votes

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