0

I want to compute the L2 norm of a n-d matrix. I want to compute this in a single statement, without introducing temporal variables. But it seems I have to, because if I write it like this, it will complains unbalanced parenthesis,

sqrt(sum((A.^2)(:)))

So I have to introduce a temporal matrix B, to write like this

B = A.^2

sqrt(sum(B(:)))

Is there any technique I can use to avoid this? I also found that if a function returns a matrix, I also cannot write like this

(fun(A))(:)

My main concern is why the operator precedence does not work here.

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
Hua
  • 184
  • 8
  • 4
    `sum(A(:).^2)`, `sum(sum(A.^2))` – David May 24 '16 at 04:59
  • 1
    Which norm exactly are you trying to calculate? Because that's not the definition of L2 norm for matrices. The L2 norm of matrices is the sum of the L2 norms of each row vector. see https://en.wikipedia.org/wiki/Matrix_norm#L2.2C1_and_Lp.2Cq_norms – ibezito May 24 '16 at 04:59
  • Your code is calculating the square of the Frobenius norm – user20160 May 24 '16 at 05:03
  • @drorco I want to calculate L2 norm. Yes, I just calculate the squared sum, I need take a square root of the sum. – Hua May 24 '16 at 05:05
  • @user20160 Yes, I need take a square root of the sum – Hua May 24 '16 at 05:05
  • @David Yes, I figured out this way. I am wondering if it is forbidden in matlab to use two pair of parenthesis next to each other. – Hua May 24 '16 at 05:07
  • yes, it is forbidden. You cannot index into an expression that has not been assigned into a variable. – Alex May 24 '16 at 05:26

1 Answers1

2

There are several approaches for solving this in one line. One option is to use the reshape function, to reshape A into a vector, as follows:

sqrt(sum(reshape(A,prod(size(A)),1).^2))

Another option is to use Matlab's builtin function:

sqrt(sum(builtin('_paren', A(:)).^2))
Community
  • 1
  • 1
ibezito
  • 5,782
  • 2
  • 22
  • 46
  • Yes, this works for 2-d matrix. If I have to handle n-d, I have to use (:), which cause the problem. – Hua May 24 '16 at 05:09