# seeking help with a for loop syntax

1 view (last 30 days)
John on 18 Nov 2013
Answered: dpb on 18 Nov 2013
Hi there,
I'm trying to write a simple for loop to simulate how the state of charge of an electric vehicle battery decreases as journeys are made. I specify the following variables before the for loop:
1. The number of journeys
2. The initial state of charge of the battery
3. The departure time and arrival time of each journey
I want to decrease the initial state of charge with each iteration of the for loop. The calculation is just the (arrival time - departure time)*1.5. I'm just learning matlab and I have attempted it below but it is completely wrong. I'd appreciate any help.
JN = 3; % Number of journeys
dt1=2; % departure time 1
at1=5; % arrival home time 1
dt2=8; % departure time 2
at2=11; % arrival time 2
dt3=8; % departure time 3
at3=11; % arrival time day 2
SOC0 = 100; % Initial state of charge
for i=1:JN
SOC(i) = SOC (i-1) - (at(i)-dt(i))*1.5
end
##### 2 CommentsShow 1 older commentHide 1 older comment
John on 18 Nov 2013

dpb on 18 Nov 2013
For the loop solution you've got to fix the references to start at one. One way is sotoo--
SOC0=100;
at=[5 11 11]; % arrival home times
dt=[2 8 8]; % departure times
SOC=zeros(JN+1,1);
SOC(1)=SOC0;
for i=1:JN
SOC(i+1) = SOC(i) - (at(i)-dt(i))*1.5;
end
Then, the "Matlab way" would be to vectorize the computation and eliminate the loop...
>> at=[5 11 11]; dt=[2 8 8];
>> SOC0=100;
>> SOC=[SOC0 cumsum(SOC0-at.*dt*1.5)]
SOC =
100 85 53 21
>>

### Categories

Find more on Manage Products 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!