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

1 visualización (últimos 30 días)
Donald Christie
Donald Christie el 27 de Abr. de 2017
Respondida: Prannay Jain el 2 de Mayo de 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:
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?

Respuestas (1)

Prannay Jain
Prannay Jain el 2 de Mayo de 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

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by