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

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

Réponses (2)

José-Luis
José-Luis le 3 Oct 2012
Modifié(e) : José-Luis le 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 commentaires

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
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)));

Connectez-vous pour commenter.

Andrei Bobrov
Andrei Bobrov le 3 Oct 2012
Modifié(e) : Andrei Bobrov le 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));

Catégories

En savoir plus sur Biotech and Pharmaceutical dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by