# How to use a for loop to add an array and matrix together?

9 views (last 30 days)
Donald Christie on 27 Apr 2017
Answered: Prannay Jain on 2 May 2017
I am currently using a for loop to populate a pre-allocated matrix of M rows, N columns, assigned to the variable SLSCMatrix.
SLSCMatrix(1,1) = InitialSLS;
% Populates row 1 with the positive integer from InitialSLS
for i = 2:m;
%calculations from row 2 onwards are completed m number of
%times, as deteremined by the function size(Xsection). This
%allows the user to change dimensions easily.
SLSCMatrix(i,:)=SLSCMatrix(i-1,:)+SLSCRise;
end
SLSCRise is 1,1 array that contains a single positive integer (user defined). This code works well and populates the matrix no matter the size. I have changed the 1,1 vector to a X,1 array with different values in each cell and would like to sequentially add each new value in a similar way to the above code.
So essentially using Pseudo-code it would do this:
= SLSMatrix[2,1]
= SLSMatrix[3,1]
This continues until SLSMatrix[M,1] is full then progresses onto the next column of SLSMatrix
= SLSMatrix [2,2]
= SLSMatrix[2,3]
This continues until SLSMatrix is filled. Would a nested for-loop be the best way to do this? What code should I add to the above for loop to make it work with an array rather than a single vector?

Prannay Jain on 2 May 2017
Below two for loops should work for your case. Fill SLSCMatrix column wise as SLSVRise is a column matrix.
for j=1:N
for i=2:M
SLSCMatrix(i,j) = SLSCMatrix(i-1,j) + SLSVRise(i-1,1)
end
end

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by