MATLAB: How to prevent overwriting of matrix elements

for loopMATLABmatrix

The matrix elements start writing correctly, but as soon as the next one gets written, all preceeding elements also get the next value applied to them for some reason. This just leaves me with the last value of the V vector as all first column and row elements
n = 5; % Matrix will be (n+1)x(n+1)
V = ZeroBased(zeros(1,n));
for i = 1:n
V(i) = i/3;
end
H = ZeroBased(zeros(n));
for cols = 0:n
for rows = 0:n
if cols == 0 % Only column 1
H(1:rows,cols) = V(rows);
elseif rows == 0 % Only row 1
H(rows,1:cols) = V(cols);
elseif rows == cols % Only diagonal (excluding 1,1 for some reason)
H(rows,cols) = rows^2 + sum(V);
else
H(rows,cols) = V(rows); % Remainder of cells
end
H(0,0) = sum(V_vals) % Necessary to have an exception statement for 1,1
end
end
I've included comments so you can see my train of thought to some degree.

Best Answer

Hi Domantas
This is just a provisional answer since I am not sure exactly what you are trying to do, but statements like
H(1:rows,cols) = V(rows); and H(rows,1:cols) = V(cols);
ensure that previous rows and columns of H are going to be overwritten, as opposed to
H(rows,cols) = whatever