solving a for loop error
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello,
I want to generate set of temperatures (V)s with the function below, when I run the code it returns error as there is no index 0;
any help would be appreciated.
v0=0; % initial temperature
t0=0; % initial time
t= rand;
x=0:0.1:5;
n=length(x);
V(k)=V(k-1)+A(t(k)-sum(from 0 to k-1)t);
For example, V(1)=V(0)+A(t-t(0)) returns error as the index value is zero which is not possible.
V(2)=V(1)+A*(t(2)-(t(0)+t(1)));
t=zeros(1,n);
v=zeros(1,n);
for k=1:n
t(k)= rand;
V(k)=V(k-1)+A*(t(k)-sum(t(k)));
end
댓글 수: 0
답변 (1개)
Prasad Reddy
2020년 4월 22일
In MATLAB for a vector the index start from 'one'(1) not 'zero'(0).
supposeif you have a vector v=[2,4,6,3,9,7]
you can axcess thosevalues as v(1) and it will return 2,
v(2) will return 4
v(3) will return 6 and so on.
if you try to axcess v(0) it will return an error, because there is no such element with 'zero;(0) as index. so try to avoid the occurence of v(0) term in your loop.
I am re writing your program, i have understood the exact location of your problem but i havent got the value of A from your program, so i am taking A=4 an writing it.
clc
clear all
v0=0 % initial temperature
t0=0 % initial time
A=2
x=0:0.1:5
n=length(x)
t=x;
v=zeros(1,n);
v(1)=v0+A*(t(1)-t0)
for k=2:n
v(k)=v(k-1)+A*(t(k)-t(k-1));
end
댓글 수: 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!