How to store value of for loop in a array
조회 수: 73 (최근 30일)
이전 댓글 표시
Hello everyone,
I am trying to store value of A in an array. But some how it stops after 3 itrations at z = 0.03.
Why So? If anybody can have a look where I going wrong.
A = zeros(1,31);
aes = 2;
counter= 1;
for z= 0:0.01:0.3
A(1, counter) = 1/(1+((z/aes)^2));
counter = counter+ 1;
end
A;
Thanks in Advance
댓글 수: 0
채택된 답변
Adam Danz
2020년 10월 14일
편집: Adam Danz
2020년 10월 14일
"some how it stops after 3 itrations at z = 0.03"
That's actually not true. In your script, z contains 4 values and the loop has 4 iterations
% First 7 values of A from your version
>> A(1:7)
ans =
1 0.99998 0.9999 0.99978 0 0 0
You're initializeing A as a 1x31 vector of zeros which is why there are extra value in the output.
There's nothing wrong with your loop but I find it more intuitive to loop over intergers 1:n rather than looping over elements of a vector directly. Consider this version,
z= 0:0.01:0.03;
A = zeros(size(z));
aes = 2;
counter= 1;
for i= 1:numel(z)
A(i) = 1/(1+((z(i)/aes)^2));
end
Result:
>> A
A =
1 0.99998 0.9999 0.99978
If you intended to have 31 iterations, define z in the first line of my version as
z = linspace(0,.03,31)
% or
z = 0 : 0.001: 0.03;
and then run the rest of my version.
Result:
A =
Columns 1 through 11
1 1 1 1 1 0.99999 0.99999 0.99999 0.99998 0.99998 0.99998
Columns 12 through 22
0.99997 0.99996 0.99996 0.99995 0.99994 0.99994 0.99993 0.99992 0.99991 0.9999 0.99989
Columns 23 through 31
0.99988 0.99987 0.99986 0.99984 0.99983 0.99982 0.9998 0.99979 0.99978
댓글 수: 2
추가 답변 (2개)
David Hill
2020년 10월 14일
A = zeros(1,31);
aes = 2;
counter= 1;
for z= 0:0.001:0.03%I believe you want the interval to be .001 (otherwise loop only runs for 4 times)
A(1, counter) = 1/(1+((z/aes)^2));
counter = counter+ 1;
end
댓글 수: 0
madhan ravi
2020년 10월 14일
for z = linspace(0, 0.03, 31)
By the way you don’t need a Loop it’s simply:
A = 1 ./ (1 + ((z / aes) .^ 2))
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!