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

1 回表示 (過去 30 日間)
Donald Christie
Donald Christie 2017 年 4 月 27 日
回答済み: Prannay Jain 2017 年 5 月 2 日
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?

回答 (1 件)

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

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by