Schnigges
Schnigges

Reputation: 1326

MATLAB Nesting Expression

Just a simple nesting question:

I've got a <100x100 double> matrix mat_B, with I cumsum. From the resulting matrix mat_A, I just need the last row vec_C, which I need to cumsum again. My code looks like this:

mat_A = cumsum(mat_B);
vec_C = cumsum(mat_A(end,:));

My question is, if it's possible to put all of this inside one line of code. I know that cumsum(mat_B) returns a matrix, but if I put (end, :) behind the expression, it won't work.

I know it sounds quite silly, but I'd like to know how nesting works in those kind of situations.

Upvotes: 1

Views: 104

Answers (1)

Buck Thorn
Buck Thorn

Reputation: 5073

You could skip the first cumsum and just use sum, since the last line of cumsum is equivalent to the result of sum:

>> mat_B=rand(5); 
>> cumsum(mat_B)

ans =

    0.2517    0.4522    0.8838    0.3751    0.2527
    0.6847    0.7778    1.3412    0.7487    0.8376
    1.5270    1.1579    2.1404    1.2327    1.3613
    1.7115    2.0444    2.2745    2.2021    1.5247
    2.2197    2.8056    2.3398    2.5442    2.0111

>> sum(mat_B)

ans =

    2.2197    2.8056    2.3398    2.5442    2.0111

Therefore

vec_C = cumsum(sum(mat_B));

should do what you want.

Upvotes: 6

Related Questions