Matlab, alternative to creating an extra vector?
Asked Answered
L

1

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?

Lightfoot answered 2/10, 2013 at 18:13 Comment(4)
Why do you need to "get everything on a single line"?Poindexter
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.Lightfoot
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.Enrichetta
possible duplicate of How can I index a MATLAB array returned by a function without first assigning it to a local variable?Consequence
E
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.

Enrichetta answered 2/10, 2013 at 19:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.