solving a for loop error

1 回表示 (過去 30 日間)
Hamzah Faraj
Hamzah Faraj 2020 年 4 月 22 日
回答済み: Prasad Reddy 2020 年 4 月 22 日
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

回答 (1 件)

Prasad Reddy
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by