Vectorization question (trying to avoid for loops)
2 views (last 30 days)
Dear all, I know that this must be quite a common question and I am sorry if the answer has already been posted somewhere, but after a good look all over this website and several other websites I still am not sure whether there is a way for me to avoid 'for' loops in my case. So here is part of my code which I am trying to vectorize:
G=zeros(t_max+1,9); %each column represents the proportion of people using something numbered 1 to 9. So: sum(G,2)=1
P=zeros(t_max+1,4); %each column represents the proportion of people using either item 1, 2, 3 or 4. So: sum(P,2)=1
SS=[1 1 2 1 1 2 3 3 4]; %each number corresponds to each column of P (item 1 to 4)
I=[a b c d e f g h i]; %with a to i, 9 preallocated numbers (basically initial proportion values)
%G(t+1,:) is updated but not shown here
for ii=1:4 %columns of P
for jj=1:9 %columns of G
Basically in plain english (well I will try my best explaining it), at each time step 't' I am updating the proportion in 'P' which is a sum of specific proportions in 'G' (I have not shown this but G(t+1,:) is calculated before the loop). Each proportion of P is updated depending on which column of P the numbers in 'SS' are specifying to. So if SS(:,6) specifies 2, we know that the proportion in the sixth column of G will be added to second column of P (cumulative sums). (I think that might be even less understandable so if you have any question just ask me).
Sorry for the really long post and hopefully someone will be able to tell me if I really need all these 'for' loops or if I can simplify it using vectorization.
Kirby Fears on 22 Jan 2016
Edited: Kirby Fears on 22 Jan 2016
I deleted the clear lines and switched the ( t_max+1) tendency to simply be t_max. I added t_max and I values up top so it runs on my machine. Here is the code with those changes:
t_max = 5; % needed a t_max value
G = zeros(t_max,9);
P = zeros(t_max,4);
SS = [1 1 2 1 1 2 3 3 4];
I = 1:9; % needed real I values
G(1,:) = I;
for t = 1:t_max,
for ii = 1:4,
for jj = 1:9,
P(t,ii) = P(t,ii) + G(t,jj);
Then I simplified your nested loops to a single loop.
for s = 1:numel(SS),
P(:,SS(s)) = P(:,SS(s)) + G(:,s);
This gives the same result as the nested loops, though G and P are mostly full of zeros still. Let us know if this is what you needed.