1

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.

Schnigges
  • 1,284
  • 2
  • 24
  • 48
  • I don't think so, I mean why do you need 1 line instead of 2 – MZimmerman6 Jul 22 '13 at 16:46
  • I don't really "need" it, I just wondered if it's possible. I'm new to MATLAB and know how nesting works in C++ or Java, but couldn't find anything about Matlab. – Schnigges Jul 22 '13 at 16:47
  • oh alright. I am not entirely sure it is without a bit of thought. – MZimmerman6 Jul 22 '13 at 16:50
  • 1
    You can't nest like this in Matlab (unfortunately). You generally have to explicitly create a new variable. If you are using a cell, you can do a little better by using `my_cell{1,2}(6,5)` to access the (6,5) element of the data contained in the container {1,2} of `my_cell` but that's about as far as it goes. – Hugh Nolan Jul 22 '13 at 17:16
  • Might be related to: http://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it – BerndGit Mar 26 '15 at 12:20

1 Answers1

6

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.

Buck Thorn
  • 5,024
  • 2
  • 17
  • 27