0

I want to write an anonymous function taking a vector theta as its input and compute the sum of the fourth-squared of the first half elements of theta:

L=@(theta) sum(theta.^4(1:length(theta)/2))

But Matlab reports an error

??? Error: File: c2n9.m Line: 3 Column: 27
Unbalanced or unexpected parenthesis or bracket.

I identified the error same as the following simpler example

>> a=ones(1,4)

a =

     1     1     1     1

>> a.^4(1:2)
??? a.^4(1:2)
        |
Error: Unbalanced or unexpected parenthesis or bracket.

>> (a.^4)(1:2)
??? (a.^4)(1:2)
          |
Error: Unbalanced or unexpected parenthesis or bracket.

I wonder how I can make the simple example as well as the anonymous function work?

Thanks!

3 Answers3

1

You could instead do

a(1:2).^4
YXD
  • 31,741
  • 15
  • 75
  • 115
  • Seems that's covered here: http://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it – YXD Feb 28 '12 at 17:06
  • @Ethan: your original code doesn't work because you can't index results like that. If you were to store the output of the `.^4` operation like `temp=a.^4; temp(1:2);` it would work; – tmpearce Feb 28 '12 at 17:08
1

you should do the indexing before the per-element raising to the power

instead of:

L=@(theta) sum(theta.^4(1:length(theta)/2))

try

L=@(theta) sum(theta(1:round(length(theta)/2)).^4)

note that I also added a round to take care of the case where the length of theta is odd

Marc
  • 5,315
  • 5
  • 30
  • 36
0

Err, aren't you missing a multiplication sign at the place that the first error message points to ? Or something else ?

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
  • There is no multiplication in my expressions. I updated my code just now. –  Feb 28 '12 at 17:01