How to avoid unwanted values in for loop

조회 수: 3 (최근 30일)
Safi ullah
Safi ullah 2018년 12월 31일
댓글: madhan ravi 2018년 12월 31일
Hi everybody, I am using the following for loop code
for j = 3:1:6
A(j)=1*10.^(-j);
end
This gives me A=[0 0 0.001 0.0001 1e-05 1e-06]
I need the value of A for j = 3, 4, 5, and 6. In the above result my desired values are (0.001 0.0001 1e-05 1e-06). I don’t know from where the first 2 values (0 0) come, which are not required here. Any guidance will be appreciated thanks

채택된 답변

madhan ravi
madhan ravi 2018년 12월 31일
편집: madhan ravi 2018년 12월 31일
Reason: The first two elements are zero because you assign the values from index three so matlab assigns the first two values as zeros because matlab index starts from one.
You don't need loop at all:
A=10.^(-(3:6));
But if you insist one then:
n=3:6;
A=zeros(1,numel(n)); % preallocate
for j = 1:numel(n)
A(j)=10.^(-n(j));
end
A
Gives:
A=[ 0.001, 0.0001, 0.00001, 0.000001]
  댓글 수: 2
Safi ullah
Safi ullah 2018년 12월 31일
In present case I need for loop your code works well @ madhan ravi thanks
madhan ravi
madhan ravi 2018년 12월 31일
Anytime :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by