MATLAB: Need to replicate a matrix in which a specific element in the matrix gets an addition

matrix addition

i = 1;
x= 5;
a = ones(3,3,3);
while i < 4
b = a;
b(i,2) = (b(i,2)+x);
i=i+1;
end
This is incorrect but any solution to how to add a number to the value in the column every loop of i would be appreciated.

Best Answer

There are a few oddities with what you have written.
First,
i = 1
while i < 4
%do something

i = i +1;
end
this is better written as simply:
for i = 1:3
%do something
end
Now, with your loop. You declare a as a 3x3x3 matrix before the loop and never change it within the loop. It therefore is a constant. At the start of the loop, you copy a into b, thus at the start of the loop, b is always a 3x3x3 matrix of 1.
You then increase an element of b. Note that b is a 3D matrix, but you only use 2D indexing. While that can work (you always get elements from b|(:, :, 1)|) it does not make sense to have a 3D matrix if you only ever use the first page.
Your element increase does work, but as said at the start of each iteration you reset b to a so whatever increase you've done is discarded. I'm not sure how to fix this because I have no idea what you're trying to do, but there is your problem.