add value from single element of array

3 views (last 30 days)
Jernej Primozic
Jernej Primozic on 10 Jul 2022
Answered: the cyclist on 10 Jul 2022
Hi. I am writting a code where i would like to add value from array. So I have one value BAT which is a number. I have an array the size of 35040x1. How can I use for loop to add one value per one iteration to increase BAT value?
So below I managed to calculate a value for bat which is one value. but then after that I dont know what to use to still use this value and go through an array
for jj = 1:length(W_br)
if jj == 1
bat(jj,1) = bat(jj,1) - W_br(jj)
if jj > 1 && jj < 5
bat(jj) = bat(jj) - W_br(jj)
Jernej Primozic
Jernej Primozic on 10 Jul 2022
Okey so i am calculating a value of battery (capcity) throuh time. I was provided with 2 elements (how much does my house use energy and how much does solar panels make)
So lets say
BAT = 7.6 consumption 3 production 5
for loop returns value: BAT = 9.7 (consumption - production)
so i have a whole array full of this 2 data but only a value for BAT
So what would I have to writte so the for loop would return actal value of BAT after going through this two arrays?
consumption: production:
0.08 0.07
0.08 0.00
0.16 0.58
0.00 0.06
BAT value after first loop is: BAT = 7.6-0.08+0.07 = 7.5
after that it should be 6.7 and so on

Sign in to comment.

Answers (1)

the cyclist
the cyclist on 10 Jul 2022
Your example is confusing to me, partly because I think you made some careless math errors. But, the way I could approach this is to calculate the cumulative consumption and production, and then just use vector math (not a for loop) to get the BAT value at every step. Something like this:
consumption = [0.08 0.08 0.16 0.00];
production = [0.07 0.00 0.58 0.06];
cumulativeConsumption = cumsum(consumption);
cumulativeProduction = cumsum(production);
BAT_initial = 7.6;
BAT = BAT_initial - cumulativeConsumption + cumulativeProduction
BAT = 1×4
7.5900 7.5100 7.9300 7.9900




Community Treasure Hunt

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

Start Hunting!