solving a for loop error

1 view (last 30 days)
Hamzah Faraj
Hamzah Faraj on 22 Apr 2020
Answered: Prasad Reddy on 22 Apr 2020
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

Answers (1)

Prasad Reddy
Prasad Reddy on 22 Apr 2020
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!