Is it possible to apply colon operator on an expression in MATLAB?

▼魔方 西西 提交于 2019-12-24 04:54:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!