seeking help with a for loop syntax

1 vue (au cours des 30 derniers jours)
John
John le 18 Nov 2013
Réponse apportée : dpb le 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 commentaires
dpb
dpb le 18 Nov 2013
Modifié(e) : dpb le 18 Nov 2013
for i=1:JN
SOC(i) = SOC (i-1) - (at(i)-dt(i))*1.5
What's the index for i=1 for the term SOC(i-1)? Matlab arrays are 1-based.
Also, the space there undoubtedly is a syntax error. You need as starters
at=[5 11 11]; % arrival home times
dt=[2 8 8]; % departure times
SOC(1)=SOC0;
for i=1:JN
SOC(i) = SOC(i-1) - (at(i)-dt(i))*1.5
end
ERRATUM:
After that I still didn't fix the 0-array addressing...changed my course in midstream and then didn't finish...
for i=1:JN
SOC(i+1) = SOC(i) - (at(i)-dt(i))*1.5;
end
This will give you a result for JN+1 entries with the first being the initial and the 2nd on the result after the previous leg.
In general you'll want to learn to preallocate as well -- that is, set
SOC=zeros(JN+1,1);
SOC(1)=SOC0;
before the loop.
Then, the "Matlab way" would be to vectorize the computation and eliminate the loop...
>> SOC0=100;
>> SOC=[SOC0 cumsum(SOC0-at.*dt*1.5)]
SOC =
100 85 53 21
>>
John
John le 18 Nov 2013
Thank you for your help

Connectez-vous pour commenter.

Réponses (1)

dpb
dpb le 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
>>

Catégories

En savoir plus sur Power and Energy Systems dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by