2

If I have this I get an error

sum(vector) == cumsum(vector)(length(vector))

>> Error: ()-indexing must appear last in an index expression.

I know I can just do:

Vec1 = cumsum(mat);
sum(mat) == Vec1(length(mat))

which will return a logical 1.

Is there an alternative to get everything on a single line?

horchler
  • 18,384
  • 4
  • 37
  • 73
  • Why do you need to "get everything on a single line"? – horchler Oct 02 '13 at 18:23
  • I was thinking that fewer variables to accomplish the same function would be better. I guess everything looks clearer on two lines rather than one though. – user2839806 Oct 02 '13 at 18:39
  • This is one of those cases where two lines is better. However, there are ways to do subscripting with the named form of the `()` operator, `subsref`. See my answer. It's just trivia, really. – chappjc Oct 02 '13 at 20:32
  • possible duplicate of [How can I index a MATLAB array returned by a function without first assigning it to a local variable?](http://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it) – Mohsen Nosratinia Oct 03 '13 at 11:03

1 Answers1

2

Well, if you are absolutely determined to do it in one line,

sum(vec) == subsref(cumsum(vec),struct('type','()','subs',{{numel(vec)}}))

But this is a borderline abuse of subsref, which is generally used for overloading the subscripting operators (i.e. {}, (), .) in custom classes.

chappjc
  • 30,359
  • 6
  • 75
  • 132