How can you include indices in a function of a discrete process?

1 view (last 30 days)
Hey everybody,
I am working on a assignment and am new to Matlab. I first made the following for loop:
>> for j=2:10 r(1)=.035 kappa=.3; theta=.03; sigma=.1; deltat=1;
r(j)=r(j-1)+kappa*(theta-r(j-1))*deltat+sigma*normrnd(0,1)*sqrt(deltat);
end
this gives me an autoregressive discrete proces. Now I want to have a function of the values of the vector r. For example if I compute
j=1:10
s=2.*r(j)
everything goes well. For my purposes however, I need to include the index itself in the function, for example
j=1:10
s=2.*r(j)+j.
Now there is an error
??? Error using ==> plus Matrix dimensions must agree.
Can anyone help me out??? Thanks very very much beforehand :)
Regards,
James

Answers (2)

José-Luis
José-Luis on 3 Oct 2012
Edited: José-Luis on 3 Oct 2012
j=1:10;
j is a row vector.
s = 2.*r(j)+j;
You are trying to add a scalar to a row vector. No can do. You can however add two vectors of the same size:
s = 2.*r + j;
  2 Comments
James van Viersen
James van Viersen on 3 Oct 2012
Thank you for your response. I see you what you mean. But how can I adjust it such that for example
s(1)=2*r(1)*exp(r(1)+2)
s(2)=2*r(2)*exp(r(2)+2)
i.e.
s(i)=2*r(i)*exp(r(i)+i) for example?
regards
José-Luis
José-Luis on 3 Oct 2012
Edited: José-Luis on 3 Oct 2012
s=2.*r.*exp(r+(1:size(r,1)));
If r is a column vector.
s=2.*r.*exp(r+(1:size(r,2)));
If r is a row vector.
s=2.*r.*exp(r+(1:numel(r)));
More general.
And if r is a matrix you can use Andrei's suggestion, assuming your data is ordered by column:
s = 2 .* r .* exp(r,reshape(1:numel(r),size(r)));

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 3 Oct 2012
Edited: Andrei Bobrov on 3 Oct 2012
r([1,10])=[.035, 0]; kappa=.3; theta=.03; sigma=.1; deltat=1;
for j1=2:10
r(j1)=r(j1-1)+kappa*(theta-r(j1-1))*deltat+sigma*normrnd(0,1)*sqrt(deltat);
end
s1 = 2*r;
s2 = 2*r + reshape(1:numel(r),size(r));

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!