Non-integer value in for-loop

조회 수: 6 (최근 30일)
U B
U B 2024년 10월 5일
댓글: Walter Roberson 2024년 10월 5일
Probably a simple question but why non-integer value can't be used in for-loop.
for i=0:.1:1
H(i)=10*i ;
end
H
how do i use any non-integer value in for-loop?
Appriciate your help.
  댓글 수: 1
Walter Roberson
Walter Roberson 2024년 10월 5일
What does H(0.1) = value mean?

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

채택된 답변

Star Strider
Star Strider 2024년 10월 5일
One approach —
iv = 0:.1:1;
for i = 1:numel(iv)
H(i)=10*iv(i) ;
end
H
H = 1×11
0 1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000 8.0000 9.0000 10.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
.

추가 답변 (1개)

Voss
Voss 2024년 10월 5일

You can't use a number that's not a positive integer as an index, as in H(i) when i is 0 or 0.1, etc.. That's the problem.

vals = 0:0.1:1; % linspace(0,1,11) might be better
N = numel(vals);
H = zeros(1,N); % pre-allocate H
for i = 1:N
    H(i) = 10*vals(i);
end

If that's all the loop does, you don't need it:

vals = 0:0.1:1;
H = 10*vals;

카테고리

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