Creating a matrix with for loop
조회 수: 6 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
Stephen23
2018년 4월 27일
편집: Stephen23
2018년 4월 27일
"It should definitely be a for loop. I don't think such a matrix can be produced using for 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?
댓글 수: 3
Stephen23
2018년 4월 27일
편집: Stephen23
2018년 4월 27일
It works when I try it:
>> n = 5;
>> L = 0.5;
>> dx = L/n;
>> [0,dx/2:dx:L,L].'
ans =
0.00000
0.05000
0.15000
0.25000
0.35000
0.45000
0.50000
This gives five values between 0 and L, just as requested. And this gives ten, just as requested:
>> n = 10;
>> L = 0.5;
>> dx = L/n;
>> [0,dx/2:dx:L,L].'
ans =
0.00000
0.02500
0.07500
0.12500
0.17500
0.22500
0.27500
0.32500
0.37500
0.42500
0.47500
0.50000
I still don't see why you think that you need a loop.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!