问题
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?
回答1:
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.
回答2:
Two options:
err = sum(abs(a(:)-b(:)));
or
err = sum(abs(reshape(a-b,[],1)));
回答3:
In this particular case, you could do sum(abs(a(:)-b(:)))
, but in general Matlab doesn't support that sort of nested indices.
来源:https://stackoverflow.com/questions/9337713/is-it-possible-to-apply-colon-operator-on-an-expression-in-matlab