Store data during for and while loops - matlab

I need some help to store values in MATLAB using the following code:
for n = 1:some number
iter = 0;
while % condition
iter = iter + 1 ;
for k = 1:9
% call the integrator 9 times
[t,s] = ode113(#(t,y) eqns, [0 t{k}], X{k}, options);
% X{k} contains 9 initial conditions where each has 6 values
x{k} = s(:,1:6)
% x{k} = stores each arc from integration
x = 1x9 cell array where each cell is #rowsx6
end
end
state(n,:) = x;
end
The issue I am having is that state does not have all n values of x. For example, if n = 2, state is size 2x9 BUT only the x values for n = 2 is stored; nothing is saved for n = 1. I also tried: state{n}(iter,:) inside the while loop and it also only stores the x data from the last iteration. It appears that the variable state is being overwritten. Can someone please point me in the right direction?

got it! thanks for inputs. variable was not assigned properly.

Related

MATLAB changing variable inside a for loop

I created the Matlab code below to implement the value of an European Put following the implementation inside this paper. I am trying to graph the value of M against the value of the European Put as M increases from 20 to 250 in time steps of 5.
In order to do this, I created a for loop to change the value of M,
for M = 20:5:250
I think that I need to create this for loop in order to change the value of M. Unit testing shows that I did something wrong. The for loop isn't working as intended. The graph produced by the code is referencing the original value of M (defined to be 200) instead of the changing values of M inside the for loop. I don't know why the code returns the original value of M instead of the values inside the for loop.
clear all;
close all;
% EURO9 Binomial method for a European put.
%
% Uses explicit solution based on binomial expansion.
% Vectorized, based on logs to avoid overflow,
% and avoids computing with zeros.
%%%%%%%%%% Problem and method parameters %%%%%%%%%%%%%
S = 9 ;E = 10 ;T = 3 ;r = 0.06 ;sigma = 0.3 ; M = 200;
dt = T/M ; A = 0.5*(exp(-r*dt)+exp((r+sigma^2)*dt)) ;
u= A + sqrt(A^2-1) ; d = 1/u ; p = (exp(r*dt)-d)/(u-d) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% cut-off index
for M = 20:5:250
z = max(1,min(M+1,floor( log((E*u)/(S*d^(M+1)))/(log(u/d)) )));
% Option values at time T
W=E-S*d.^([M:-1:M-z+1]').*u.^([0:z-1]');
% log/cumsum version using cut-off index z
tmp1 = cumsum(log([1;[M:-1:M-z+2]'])) - cumsum(log([1;[1:z-1]']));
tmp2 = tmp1 + log(p)*([0:z-1]') + log(1-p)*([M:-1:M-z+1]');
value = exp(-r*T)*sum(exp(tmp2).*W);
disp('M is'), disp(M)
disp('Option value is'), disp(value)
hold on;
xlabel('M') % x-axis label
ylabel('European Put') % y-axis label
plot(M,value,'r*')
end
Unit testing shows that my code is wrong. Testing against M=20 returns a value less than one when the true value is 1.5076.
Did I write the for loop completely wrong? Why is it referencing the value of M=200 at every iteration instead of the increment specified in the for loop for M = 20:5:250?
As an example, running
clear all;
close all;
% EURO9 Binomial method for a European put.
%
% Uses explicit solution based on binomial expansion.
% Vectorized, based on logs to avoid overflow,
% and avoids computing with zeros.
%%%%%%%%%% Problem and method parameters %%%%%%%%%%%%%
S = 9 ;E = 10 ;T = 3 ;r = 0.06 ;sigma = 0.3 ; M = 20;
dt = T/M ; A = 0.5*(exp(-r*dt)+exp((r+sigma^2)*dt)) ;
u= A + sqrt(A^2-1) ; d = 1/u ; p = (exp(r*dt)-d)/(u-d) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% cut-off index
z = max(1,min(M+1,floor( log((E*u)/(S*d^(M+1)))/(log(u/d)) )));
% Option values at time T
W=E-S*d.^([M:-1:M-z+1]').*u.^([0:z-1]');
% log/cumsum version using cut-off index z
tmp1 = cumsum(log([1;[M:-1:M-z+2]'])) - cumsum(log([1;[1:z-1]']));
tmp2 = tmp1 + log(p)*([0:z-1]') + log(1-p)*([M:-1:M-z+1]');
value = exp(-r*T)*sum(exp(tmp2).*W);
disp('M is'), disp(M)
disp('Option value is'), disp(value)
returns
Option value is
1.5076
and running
clear all;
close all;
% EURO9 Binomial method for a European put.
%
% Uses explicit solution based on binomial expansion.
% Vectorized, based on logs to avoid overflow,
% and avoids computing with zeros.
%%%%%%%%%% Problem and method parameters %%%%%%%%%%%%%
S = 9 ;E = 10 ;T = 3 ;r = 0.06 ;sigma = 0.3 ; M = 25;
dt = T/M ; A = 0.5*(exp(-r*dt)+exp((r+sigma^2)*dt)) ;
u= A + sqrt(A^2-1) ; d = 1/u ; p = (exp(r*dt)-d)/(u-d) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% cut-off index
z = max(1,min(M+1,floor( log((E*u)/(S*d^(M+1)))/(log(u/d)) )));
% Option values at time T
W=E-S*d.^([M:-1:M-z+1]').*u.^([0:z-1]');
% log/cumsum version using cut-off index z
tmp1 = cumsum(log([1;[M:-1:M-z+2]'])) - cumsum(log([1;[1:z-1]']));
tmp2 = tmp1 + log(p)*([0:z-1]') + log(1-p)*([M:-1:M-z+1]');
value = exp(-r*T)*sum(exp(tmp2).*W);
disp('M is'), disp(M)
disp('Option value is'), disp(value)
returns
Option value is
1.4666
Although, I don't get these values in the graph of the for loop for M = 20:5:250. I must have made a mistake inside the for loop.
The problem is with M. You initialised M=200 before the start of the loop which is affecting all the calculations that you're doing before the loop. Whereas in the two unit tests that you have provided, you used M=20 and M=25 for all the calculations respectively.
So the fix is to simply move the calculations that are affected by M inside the loop. i.e
S=9; E=10; T=3; r=0.06; sigma=0.3;
for M = 20:5:250
dt = T/M;
A = 0.5*(exp(-r*dt)+exp((r+sigma^2)*dt)) ;
u = A + sqrt(A^2-1);
d = 1/u;
p = (exp(r*dt)-d)/(u-d);
%And here goes what you already have in your loop
%....
%....
end

parfor doesn't consider information about vectors which are used in it

This is a part of my code in Matlab. I tried to make it parallel but there is an error:
The variable gax in a parfor cannot be classified.
I know why the error occurs. because I should tell Matlab that v is an incresing vector which doesn't contain repeated elements. Could anyone help me to use this information to parallelize the code?
v=[1,3,6,8];
ggx=5.*ones(15,14);
gax=ones(15,14);
for m=v
if m > 1
parfor j=1:m-1
gax(j,m-1) = ggx(j,m-1);
end
end
if m<nn
parfor jo=m+1:15
gax(jo,m) = ggx(jo,m);
end
end
end
Optimizing a code should be closely related to its purpose, especially when you use parfor. The code you wrote in the question can be written in a much more efficient way, and definitely, do not need to be parallelized.
However, I understand that you tried to simplify the problem, just to get the idea of how to slice your variables, so here is a fixed version the can run with parfor. But this is surely not the way to write this code:
v = [1,3,6,8];
ggx = 5.*ones(15,14);
gax = ones(15,14);
nn = 5;
for m = v
if m > 1
temp_end = m-1;
temp = ggx(:,temp_end);
parfor ja = 1:temp_end
gax(ja,temp_end) = temp(ja);
end
end
if m < nn
temp = ggx(:,m);
parfor jo = m+1:15
gax(jo,m) = temp(jo);
end
end
end
A vectorized implementation will look like this:
v = [1,3,6,8];
ggx = 5.*ones(15,14);
gax = ones(15,14);
nn = 5;
m1 = v>1; % first condition with logical indexing
temp = v(m1)-1; % get the values from v
r = ones(1,sum(temp)); % generate a vector of indicies
r(cumsum(temp)) = -temp+1; % place the reseting locations
r = cumsum(r); % calculate the indecies
r(cumsum(temp)) = temp; % place the ending points
c = repelem(temp,temp); % create an indecies vector for the columns
inds1 = sub2ind(size(gax),r,c); % convert the indecies to linear
mnn = v<nn; % second condition with logical indexing
temp = v(mnn)+1; % get the values from v
r_max = size(gax,1); % get the height of gax
r_count = r_max-temp+1; % calculate no. of rows per value in v
r = ones(1,sum(r_count)); % generate a vector of indicies
r([1 r_count(1:end-1)+1]) = temp; % set the t indicies
r(cumsum(r_count)+1) = -(r_count-temp)+1; % place the reseting locations
r = cumsum(r(1:end-1)); % calculate the indecies
c = repelem(temp-1,r_count); % create an indecies vector for the columns
inds2 = sub2ind(size(gax),r,c); % convert the indecies to linear
gax([inds1 inds2]) = ggx([inds1 inds2]); % assgin the relevant values
This is indeed quite complicated, and not always necessary. A good thing to remember, though, is that nested for loop are much slower than a single loop, so in some cases (depend on the size of the output), this will may be the fastest solution:
for m = v
if m > 1
gax(1:m-1,m-1) = ggx(1:m-1,m-1);
end
if m<nn
gax(m+1:15,m) = ggx(m+1:15,m);
end
end

MATLAB LOOPS: Inserting values from a big array to a small array

I have a vector named signal consisting of 300001 values. In each iteration of the for loop, I want to pick up 2000 consecutive values from this vector and store it in another vector X (X is 1*2000 vector)
The code is as follows:
D = 1:300001;
A = zeros(1,2000);
r=1;
n=0;
m=1;
for i=1:300001
for p = (1+(2000*n)):(r*2000)
while m<2000
A(1,m)= signal(1,p);
%disp (m);
m = m+1;
end
end
r = r+1;
n = n+1;
m = 1;
end
But it gives me the error "Index exceeds matrix dimensions.
Can somebody help me out with a better way to do it?
this would work
signal = ones(1,30000);
index1= 1:2000:length(signal);
index2= 2000:2000:length(signal);
for i=1:length(index1)
A = signal(index1(i):index2(i));
end
or this
signal = ones(1,30000);
temp = reshape(signal,2000,[]);
for i = 1:size(temp,2)
A=temp(:,i);
end

Matlab index with specific values using loop

I know how to write the program with a given number of entries, but not when if the number of entries are n:. Basically I think I need a loop but I can't get it to work properly.
This is a code that works fine when having 3 entries. % is what I put in. I want to create a vector with specific position and values, this is a example how the vector would look like:
X = [1;0;0;0;0;0;0;0;0;0;0;0;0;0;99;0;0;0;0;99]
and the code for it:
n1 = input('Determine value for case:'); %n1 = 1
n2 = input('Determine value for case:'); %n2 = 15
n3 = input('Determine value for case:'); %n3 = 20
X = zeros(20,1);
X(n1) = input('Determine position '); %1
X(n2) = input('Determine position '); %99
X(n3) = input('Determine position '); %99
But for n entries, I need a loop I figured. (the vector may still be 20x1)
for n = 1:entries (%entries are 3, so 3 loops)
n = n+1
n = input('Determine value for case :');
X =zeros(20,1);
X(n) = input('Determine position:')
end
But I can't just get it to work
thanks in advance
Not sure exactly what you are trying to achieve, but I think that you can fix your loop as follows:
entries = 3;
X =zeros(20,1);
for ni = 1:entries
n = input('Determine value for case :');
X(n) = input('Determine position:');
end

How to add character to numeric matrix in matlab?

In matlab usually we add a header using fprintf command.
This is a problem when the size of the table depends on the input and when it exceeds a certain range (more than total number of column able to be presented in the command window).
When this occurs the header which we specified previously using the fprintf command will not be compatible with the current output data.
I would like to know is there a way like adding a character string into the 1st row of the matrix during some kind of iteration process. I had tried hardly but still can't find a proper way to solve this issue.
Or it is actually cannot be done in matlab for this purpose.
Eg
clear;clc
A = [2 8 3 1;0 2 -1 4;7 -2 1 2;-1 0 5 2]
B = [-2;4;3;5]
Es = 1e-5
n = length(B);
x = zeros(n,1);
Ea = ones(n,1);
iter = 0;
while max(Ea) >= Es
if iter <= 30
iter = iter + 1;
x_old = x;
for i = 1:n
j = 1:n;
j(i) = [];
x_cal = x;
x_cal(i) = [];
x(i) = (B(i) - sum(A(i,j) * x_cal)) / A(i,i);
end
else
break
end
x_ans(:,iter) = x;
Ea(:,iter) =abs(( x - x_old) ./ x);
end
result = [1:iter; x_ans; Ea]'
for the coding above..how could I add the heading like iteration for 1st column, x1...x2...x3..xn for nth column and error x1..error x2..error xn for another n column. I would like to make this heading can be automated generated based on the input matrix
If the size of the table depends on the input, use a cell array, using c = cell(...).
In each iteration simply call c{i,j} instead of c[i,j].