Matlab code to charge to a maximum value of capacity - matlab

I want to get rCl, which is remaining charge of a battery in an e-vehicle. Currently the values are wrong as I am not getting the code right.
rCl should be a max of 1000. nCl describes the amount (in kWh) it is using, and pCp the amount (in kWh), it could potentially load. So it should be like that:
rCl(x) = rCl(x-1) -nCl(x-1) + pCp(x-1) --> to a a max of 1000kWh
I tried several things, including this:
for x = 2:2:2734
Cp(x) = min(nC(x-1),pCp(x))
end
for x = 2:1:2734
rC(x) = rC(x-1) - nC(x-1) + Cp(x-1)
end
But I just cant figure it out - I might have been looking at it for to long already... any suggestions are welcome!
If you look at the pic of the data, you may notice, it works as long as pCp is greater than nCl and therefor it can load to full. Once this is not working anymore, the load never goes to full again and keeps on decreasing.

I figured it out:
for x = 2:1:tablesize
rCl(x) = rCl(x-1)-nCl(x-1)+pCp(x-1)
if rCl(x) > 1000
rCl(x) = 1000
end
end

Related

Matlab get amount of clipping

Hi I am trying to measure the amount of clipped Samples in audio files with matlab. That means i want to get the number of all Samples that are at the Fullscale Value (at min and max). But it should just count them when there are at least two following samples at this Value.
My code so far:
for i = 1 :20
fileName = ['Elektro',num2str(i) '.wav'];
unclipped = audioread(fileName);
summeMax = sum(1 ==unclipped);
summeMin = sum(-1==unclipped);
summe = summeMin +summeMax;
str=sprintf('%d ',summe);
disp(str);
end
As you see its counting every sample and I would need a loop and if statements to detect if there are more than one sample at the fullscale Value.
I tried this it with a loop from j = 1 : length(unclipped) but it takes to long with this Method.
Anyone have suggestions how i could do this?
As #Daniel pointed out in his answer to a previous question of yours, you can find all samples at which the maximum is reached by
maxReached = max(unclipped(:))==unclipped;
To remove all places where the maximum is reached for only one sample, you can use a morphological opening with the structuring element [1,1]:
clippedSamples = imopen(maxReached, [1 1]);
The number of clipped samples is now
sum(clippedSamples);
Of course you'll have to do the same with those samples where the minimum is reached.

Matlab: variable index size in loop

I've been trying to figure this out myself and also searched here. The fact that I am not quite sure what the problem is isn't helping with this. I have previously found good help in answers to other people here, so I hope that you can help me.
I have a dataset (2000x1100) that consists of 1's and 0's, where each row represents one datapoint over time (columns).
I am trying to find sequences of 0's for each row and exclude those that are below a specific length. I have already found helpful answers here that allowed me to do this (thanks!).
'test' is a reduced test dataset that I am using to test the code.
for j = 1:size(test,1)
testThresh(j,:) = diff([1 test(j,:)]);
startIndex = find(testThresh(j,:) < 0);
if isempty(startIndex)
continue
j = j+1;
end
endIndex = find(testThresh(j,:) > 0)-1;
if numel(endIndex) == 1
for m = 1:size(startIndex,2)
duration = (endIndex(m)-startIndex(m))+1;
threshold = (duration < 10);
startIndexC = startIndex(threshold);
endIndexC = endIndex(threshold);
end
else
duration = (endIndex(j,:)-startIndex(j,:))+1;
threshold = (duration < 10);
startIndexC = startIndex(threshold);
endIndexC = endIndex(threshold);
end
..
I would later replace the below-threshold sequences of 0's with 1's.
The code works fine until I happen to have a row that doesn't contain any 0's. It would skip to the next row as supposed to, but there it will result in an error:
Attempted to access endIndex(2,:); index out of bounds because size(endIndex)=[1,4].
I don't really understand why this causes an error. There isn't any problem with this specific row if it isn't preceded by a no-zero-containing row.
I assume that encountering a row w/o 0 does something to the allowed size of the array. I don't really know how to get around it. I can't pre-allocate because I don't know the size the variable will reach in each iteration (I tried anyway and it didn't help).
I also tried to say that numel(endIndex) >= 1 otherwise skip to next step. That also didn't work. I probably made a really silly mistake, but I am still quite new to Matlab and just can't figure it out.
I hope anyone can help with this!
Any help is greatly appreciated!
Edit:
duration = (endIndex(1,:)-startIndex(1,:))+1;
This is very stupid. I am ashamed. Thanks for pointing this out.
Just for reasons of completion since I wasn't specific enough of what I want to accomplish (sorry about that): I want to determine the start, end and length of stretches of 0's within a lot of 1's. If the length of any of these stretches is below the threshold of 10 (i.e. too short for my purposes to be considered) I want to disregard it.

How to run the code for large variables

I have one code like below-
W = 3;
i = 4;
s = fullfact(ones(1,i)*(W + 1)) - 1;
p2 = unique(sort(s(sum(s,2) == i,:),2),'rows');
I can run this code only upto "i=11" but i want to run this code for upto "i=25".When i run these code for i=12 it shows error message "Out of Memory".
I need to keep these code as it is.How can i modify these code for larger value of "i"?
Matlab experts need your valuable suggestion.
Just wanting to do silly things is not enough. You are generating arrays that are simply too large to fit into memory.
See that the size of the matrix s is a function of i here. size(s) will be 2^(2*i) by i. (By the way, some will argue it is a bad idea to use i as a variable, which is normally sqrt(-1), for such variables.)
So when i = 4, s is only 256x4.
When i = 11, s is 4194304x11. This array takes 369098752 bytes of space, so 370 megabytes.
When i = 25, the array will be of size
2^50*25
ans =
2.8147e+16
Multiply that by 8 to get the memory needed. Something like 224 petabytes of memory! If you have that much memory, then send me a few terabytes of RAM. You won't miss them.
Yes, there are times when MATLAB runs out of memory. You can get the amount of memory available at any point of time by executing the following:
memory
However, I would suggest follow one of the strategies to reduce memory usage available here. Also, you might want to clear the variables which are not required in every iteration by
clear variable_name

MATLAB program takes more and more of my memory

I'm going to write a program in MATLAB that takes a function, sets the value D from 10 to 100 (the for loop), integrates the function with Simpson's rule (the while loop) and then displays it. Now, this works fine for the first 7-8 values, but then it takes longer time and eventually I run out of memory, and I don't understand the reason for this. This is the code so far:
global D;
s=200;
tolerance = 9*10^(-5);
for D=10:1:100
r = Simpson(#f,0,D,s);
error = 1;
while(error>tolerance)
s = 2*s;
error = (1/15)*(Simpson(#f,0,D,s)-r);
r = Simpson(#f,0,D,s);
end
clear error;
disp(r)
end
mtrw's comment probably already answers the question in part: s should be reinitialized inside the for loop. The posted code results in s increasing irreversibly every time the error was too large, so for larger values of D the largest s so far will be used.
Additionally, since the code re-evaluates the entire integration instead of reusing the previous integration from [0, D-1] you waste lots of resources unless you want to explicitly show the error tolerance of your Simpson function - s will have to increase a lot for large D to maintain the same low error (since you integrate over a larger range you have to sum up more points).
Finally, your implementation of Simpson could of course do funny stuff as well, which no one can tell without seeing it...

How to calculate value of short options call with Black-Scholes formula?

I am trying to calculate the profit/loss of a short call at various times in the future, but it isn't coming out correct. Compared to the time of expiration, the ones with time left have less profit above the strike price, but at some point below the strike they don't lose value as fast as the t=0 line. Below is the formula in pseudocode, what am I doing wrong?
profit(stockprice) = -1 * (black_scholes_price_of_call(stockPrice,optionStrike,daysTillExpiration) - premium);
Real matlab code:
function [ x ] = sell_call( current,strike,price,days)
if (days > 0)
Sigma = .25;
Rates = 0.05;
Settle = today;
Maturity = today + days;
RateSpec = intenvset('ValuationDate', Settle, 'StartDates', Settle, 'EndDates',...
Maturity, 'Rates', Rates, 'Compounding', -1);
StockSpec = stockspec(Sigma, current);
x = -1 * (optstockbybls(RateSpec, StockSpec, Settle, Maturity, 'call', strike) - price);
else
x = min(price,strike-current-price);
end
end
Your formula ain't right. I don't know why you need that leading -1 as a multiplier for, because when I distribute it out the "formula" is a simple one:
profit(stockprice) = premium - black_scholes_price_of_call(stockPrice,optionStrike,daysTillExpiration);
Pretty simple. So that means the problem is buried in that function for the price of the call, right?
When I compare your formula to what I see as the definition on Wikipedia, I don't see a correspondence at all. Your MATLAB code doesn't help, either. Dig into the functions and see where you went wrong.
Did you write those? How did you test them before you assembled them into this larger function. Test the smaller blocks before you assemble them into the bigger thing.
What baseline are you testing against? What known situation are you comparing your calculation to? There are lots of B-S calculators available. Maybe you can use one of those.
I'd assume that it's an error in your code rather than MATLAB. Or you've misunderstood the meaning of the parameters you're passing. Look at your stuff more carefully, re-read the documentation for that function, and get a good set of baseline cases.
I found the problem, it had to do with the RateSpec argument. When you pass in a interest rate, it affects the option pricing.