After learning basic programming in Java, I found that the hardest part of moving to MatLab for my current course in the algorithm is to avoid loops. I know that there are many clever ways to vectorize operations in MatLab, but my mind is so stuck in loop thinking that it’s hard for me to intuitively see how I can vectorize code. Once they show me how to do this, it makes sense to me, but I just don't see it easily. I currently have the following code for finding the barycentric weights used in Lagrangian interpolation:
function w = barycentric_weights(x); % The function is used to find the weights of the % barycentric formula based on a given grid as input. n = length(x); w = zeros(1,n); % Calculating the weights for i = 1:n prod = 1; for j = 1:n if i ~= j prod = prod*(x(i) - x(j)); end end w(i) = prod; end w = 1./w;
I'm sure there should be a smarter way in MatLab to do this, but I just can't think about it. If anyone has any advice, I will be very grateful :). And the only way that I will ever recognize all the vectorization tricks in MatLab is to see how they are used in various scenarios like the one above.
source share