Is this a valid vectorization of my loop?
Show older comments
I have a loop that I want to calculate that looks like this:
TiltedGroundreflected = zeros(1440, length(Tilt), size(UpScaledBotGlobal,2));
for minute = 1:1440
for beta = 1:length(Tilt)
for lambda=1:length(Template)
TiltedGroundreflected(minute,beta,lambda)=GrassReflectance(lambda)*UpScaledBotGlobal(minute,lambda)*(1-cosd(Tilt(beta)))/2;
end
end
end
It takes extremely long time to run because of the third for loop (the lambda one), so I wanted to see if I could speed it up. Each lambda represents a wavelength and the loop gets a corresponding reflectance value of grass for each certain wavelength and multiplies with an incident wavelength coming from the sun stored in UpScaledBotGlobal(minute,lambda). So since the wavelength is changing each iteration Im not sure if it can be vectorised or it has to be slow? Anyway, I tried to get rid of the lambda and speed it up by rewriting it like this:
TiltedGroundreflected = zeros(1440, length(Tilt), size(UpScaledBotGlobal,2));
for minute = 1:1440
for beta = 1:length(Tilt)
c=GrassReflectance(:)'.*UpScaledBotGlobal(minute,:);
TiltedGroundreflected(minute,beta,:)=c*(1-cosd(Tilt(beta)))/2;
end
end
And the calculation did go at least 100 times faster, which is great. But since I’m new to vectorization and don’t really 100% know what I’m doing (especially with the “.*”, that symbol is basically just something I try when Matlab won’t accept normal multiplication) my question is – is this correct? Am I calculating the same thing here or should I have written it in a different way?
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing 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!