How can I get my matrix to populate with correct values from for loop?
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello. I first create a matrix by using logspace and I convert it to a 50 row and 1 column matrix. I then create a for loop that polpulates column 2 per the number obtained from my for loop, (50 iterations). The values from my column one are used inside the for loop. The first iteration is done perfectly. Values (1,1) was used and populated value (1,2) . When my for loop continues to iteration 2 to 50, the rest of colum 2 is populted by 1's. Can someone please help me understand why it does not do as it first did?
format long
h = logspace(-9, -4);
h = h'
for j = 1 : 50
eps = h(j,1)
for i = 1 : 101
c = xm;
xm = (xa + xb) / 2;
t(i) = abs((xm - c ) / xm);
if t(i) <= eps
break
end
if t(i) > eps
if y(xa) < 0 && y(xm) > 0
xb = xm;
end
if y(xa) > 0 && y(xm) < 0
xb = xm;
end
if y(xm) < 0 && y(xb) > 0
xa = xm;
end
if y(xm) > 0 && y(xb) <0
xa = xm;
end
end
if i == 100
break
end
i = i + 1;
end
h(j, 2) = (i)
j = j + 1
end
p = h(:,1);
k = h(:,2);
semilogx(p,k)
댓글 수: 0
채택된 답변
Walter Roberson
2021년 3월 9일
xm = (xa + xb) / 2;
You do not reset xa and xb to their original values for each j value.
추가 답변 (1개)
KALYAN ACHARJYA
2021년 3월 9일
편집: KALYAN ACHARJYA
2021년 3월 9일
When my for loop continues to iteration 2 to 50, the rest of colum 2 is populted by 1's. Can someone please help me understand why it does not do as it first did?
Here discussion on Why Only?
Here you are trying to populate the h, 2nd column data, with i's value. The simplest way, the code can be represents as below
for j = 1 : 50
for i =1:101
%
end
h(j,2)=i;
end
Can you notice here, how does nesting loop works?
For the first iteration j=1 and inner loop runs from i=1 to 101, hen it assigned the latest i value to h
h(1,2)=101; % Latest i iteration value from the inner loop.
Next for the 2nd iteration j=2 and inner loop runs from i=1 to 101, then it assigned the latest i value to h
h(2,2)=101; % Latest i iteration value from the inner loop.
Next for the 3rd iteration j=3 and inner loop runs from i=1 to 101, then it assigned the latest i value to h
h(3,2)=101; % Latest i iteration value from the inner loop.
............
You will get the all same values in the 2nd columns of h
h =
0.0000 101.0000
0.0000 101.0000
0.0000 101.0000
0.0000 101.0000
0.0000 101.0000
0.0000 101.0000
................
What next: You have to improve the code, see the Basic here
댓글 수: 2
KALYAN ACHARJYA
2021년 3월 9일
Now, I have notices that.
if t(i) <= eps
break
end
Hope you got the idea, now how to solve
참고 항목
카테고리
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!