How to use a for loop to add an array and matrix together?
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
Prannay Jain
2017-5-2
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!