MATLAB: Creating a matrix with for loop

forfor loopif statementmatrixmatrix manipulation

I need to create a matrix that increases or decreases in size with the change in variable n. The matrix should be having only one column and the number of rows need to change with the n value.
The inputs are n, (dx=L/n), L. The matrix that needs to be created should be [0;dx/2;(dx/2+dx);((dx/2+dx)+dx);(((dx/2+dx)+dx)+dx);…..;0.5].
The fourth value of the matrix is simply the third value +dx, this should go on until it reaches 0.5. I can't seem to work out how to make a for loop for this problem.
The number of values in between 0 and 0.5 should also be equal to the n value, so if the n value is 8 the number of values in between should also be 8.

Best Answer

"It should definitely be a for loop. I don't think such a matrix can be produced using for loop"
Using colon and concatenation, without any loop:
[0,dx/2:dx:L,L].'
Try it yourself, I don't see any difference from what you requested (shown in vector A):
>> n = 8;
>> L = 0.5;
>> dx = L/n;
>> A = [0;dx/2;dx/2+dx;dx/2+2*dx;dx/2+3*dx;dx/2+4*dx;dx/2+5*dx;dx/2+6*dx;dx/2+7*dx;0.5];
>> B = [0,dx/2:dx:L,L].';
>> [A,B]
ans =
0.00000 0.00000
0.03125 0.03125
0.09375 0.09375
0.15625 0.15625
0.21875 0.21875
0.28125 0.28125
0.34375 0.34375
0.40625 0.40625
0.46875 0.46875
0.50000 0.50000
>> A-B
ans =
0
0
0
0
0
0
0
0
0
0
Why do you need to use a loop?