So I have been thinking about this for some time. Summing up some variable of array A is as simple as
sum(A(:)) % or sum(...sum(sum(A,n),n-2)...,1) % where n is the dimension of A
However, as soon as it receives expressions, (:) no longer works, for example
sum((A-2*A)(:))
is not a valid matlab syntax, instead we need to write
foo = A-2*A; sum(foo(:)) %or the one liner sum(sum(...sum(A-2*A,n)...,2),1) % n is the dimension of A
One insert above will only work if the dimension A is fixed, which, depending on what you are doing, may not be necessary. The drawback of the two lines is that foo will remain in memory until you run clear foo or even be able to depend on the size of A and what else is in your workspace.
Is there a general way to get around this problem and summarize all elements of an expression with an array estimate in one line / without creating temporary variables? Something like sum(A-2*A,'-all') ?
Edit : it is different from How can I index the MATLAB array returned by a function without first assigning a local variable? , since this does not apply to the general (or specific) indexing of values ββexpressed in an array or return values, but rather to summation over each possible index.
While you can solve my problem with the answer provided in the link, Gnowitz tells himself that using subref is a rather ugly solution. Then Andras Dick posted a much cleaner way to do this in the comments below.
user2457516
source share