jdoubleu
jdoubleu

Reputation: 73

How to define "initial value" for a calculation in MATLAB?

I have a vector a=[1,2,3,4,5,6,7] and an initial value a(0)=0 for the following equation:

for k=1:n
    delta=a(k)-a(k-1);
end

I cant define a(0)=0. Any ideas how to calc delta=a1-a0 ?

Upvotes: 0

Views: 152

Answers (2)

itzik Ben Shabat
itzik Ben Shabat

Reputation: 927

MATLAB indexing starts at 1 and not 0. so what you did will work if you simply do this:

a=[0,1,2,3,4,5,6,7];

for k=2:n 
  delta(k-1)=a(k)-a(k-1); 
end

or if you dont want to change the vector :

a=[1,2,3,4,5,6,7];

for k=1:n 
  if k>1
  delta(k-1)=a(k)-a(k-1);
  else 
  delta(1)=a(k);
end

or better yet, without the if

a=[1,2,3,4,5,6,7];
delta(1)=a(1);
for k=2:n 
  delta(k-1)=a(k)-a(k-1);    
end

Upvotes: 1

Dom
Dom

Reputation: 1722

There's a few ways to accomplish this. The simplist IMO is to use an if statement to check if k==1, then the inital condition applies:

delta = 0
for k = 1:n
    if k == 1
        delta=a(k)-0;
    else
        delta=a(k)-a(k-1);
    end
end

Upvotes: 0

Related Questions