0

If I use this syntax:

mX=[1:5];
A=rand(5,1);
C(mX)=sum(A(1:mX));

Why doesn't the content of C(mX) vary with varying mX?

Instead of doing

C(1)=A(1) 
C(2)=A(1)+A(2), etc

it does:

C(1)=A(1)
C(2)=A(1)
C(3)=A(1), etc

Is there any way to vary C(mX) without resorting to a loop?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
user1021
  • 5
  • 2

2 Answers2

2

To answer your first question:

mX=1:5;
A=rand(5,1);
C(mX)=sum(A(1:mX));

makes the sum over A(1:[1 2 3 4 5]), which results in A(1:1), and hence all your C(mX) values will be filled with purely the element A(1).

What you want to do is make a cumulative sum, which can be done, as @leanderMoesinger mentioned with cumsum:

A=rand(5,1);
C = cumsum(A)
C =
    0.0975
    0.3760
    0.9229
    1.8804
    2.8453

If you want to learn more about indexing I can highly recommend the following post: Linear indexing, logical indexing, and all that

If you want not all elements of A, but e.g. up to element three you can do

mX = 1:3;
A = rand(5,1);
C = cumsum(A(mX)); calculate only to mX

mX = [1 3 5];
C = cumsum(A(mX)) % Also works if you only want elements 1 3 and 5 to appear

% If you want elements of C 1 3 and 5 use 
tmp = cumsum(A);
C = tmp(mX);
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • Thank you for answer . But I still have a question : Supposing that I will do an operation that will include matrixs instead of arrays (for example `C(mX,mY)=sum(sum(A(1:mX,1:mY).*B(2:mX+1,2:mY+1)))` How can I vary mX and mY ? ( It will do this operation only for mX=mY=1)) – user1021 Jul 04 '17 at 11:41
  • @user1021 the size of the two matrices after indexing needs to be equal in order to work. Presumably your indices don't guarantee that. But if you have a different question (which this is, as it is about element wise matrix multiplication, the sum is just fluff) please ask a new question. – Adriaan Jul 04 '17 at 14:12
0

You can do this by cumsum like so:

mX=[1:5];
A=rand(5,1);
C = cumsum(A(mX));
OmG
  • 18,337
  • 10
  • 57
  • 90