|
"Corey Scheip" wrote in message <it815a$ij2$1@newscl01ah.mathworks.com>...
> "Charles Dillon" wrote in message <it7vvt$es8$1@newscl01ah.mathworks.com>...
> > I have been attempting to write a programme to run through all possible combinations of elements from two lists and add the results of a calculation on each pair together. the following is my current code, which works:
> >
> > function ans = cor(train1, train2, tau)
> > ans = 0;
> > length1 = numel(train1);
> > length2 = numel(train2);
> > for n=1:length1
> > for m= 1:length2
> > ans = ans + exp(-abs(train1(n) - train2(m))/tau);
> > end
> > end
> > end
> >
> > tau is a scalar, while train1 and train2 are vectors of variable length. Can anyone give me a tip as to how to replace the for loops with something that will work faster?
> >
> > I'm quite new to MATLAB, so I apologise if it's something trivially easy that I've missed.
>
>
> I can't get rid of both loops, but can offer a suggestion to get rid of one of the loops:
>
> %%%%%%%%%%%%%%%%
> function ans = cor(train1, train2, tau)
> ans = 0;
> for n=1:numel(train1) % length1 assignment unnecessary
> ans = ans + sum(exp(-abs(train1(n) - train2)/tau));
> end % for loop
>
> end % function loop
>
> %%%%%%%%%%%%%%
>
> ans + exp(-abs(train1(n) - train2)/tau); % this will give you a [1 x length(train2)] matrix, so I've added the "sum" command to add them all up and then add that value to the "ans" value.
>
> Help any?
Thanks for the help! I ended up going with Roger's suggestion, but thank you for the contribution nonetheless. My reason for the length1 assignment was that I thought that calling the numel function on every iteration of the loop would take up time. A lecturer told me that it was good practice, though he was referring to C++ at the time. Thanks again!
|