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

9 views (last 30 days)
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:
Add SLSVRise[1,1] to SLSMatrix[1,1]
= SLSMatrix[2,1]
Add SLSVRise [2,1] to SLSMatrix[2,1]
= SLSMatrix[3,1]
Add SLSVRise [3,1] to SLSMatrix[3,1]
This continues until SLSMatrix[M,1] is full then progresses onto the next column of SLSMatrix
Add SLSVRise[1,1] to SLSMatrix[1,2]
= SLSMatrix [2,2]
Add SLSVRise[2,1] to 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?

Answers (1)

Prannay Jain
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

Community Treasure Hunt

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

Start Hunting!

Translated by