seeking help with a for loop syntax

조회 수: 1 (최근 30일)
John
John 2013년 11월 18일
답변: dpb 2013년 11월 18일
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
dpb
dpb 2013년 11월 18일
편집: dpb 2013년 11월 18일
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 2013년 11월 18일
Thank you for your help

댓글을 달려면 로그인하십시오.

답변 (1개)

dpb
dpb 2013년 11월 18일
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
>>

카테고리

Help CenterFile Exchange에서 Power and Energy Systems에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by