Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding loops in MatLab code (barycentric weights)

After having learned basic programming in Java, I have found that the most difficult part of transitioning to MatLab for my current algorithm course, is to avoid loops. I know that there are plenty of smart ways to vectorize operations in MatLab, but my mind is so "stuck" in loop-thinking, that I am finding it hard to intuitively see how I may vectorize code. Once I am shown how it can be done, it makes sense to me, but I just don't see it that easily myself. Currently I 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 am pretty sure there must be a smarter way to do this in MatLab, but I just can't think of it. If anyone has any tips I will be very grateful :). And the only way I'll ever learn all the vectorizing tricks in MatLab is to see how they are used in various scenarios such as above.

like image 627
Kristian Avatar asked Feb 19 '23 17:02

Kristian


2 Answers

One has to be creative in matlab to avoid for loop:

[X,Y] =meshgrid(x,x)
Z = X - Y
w =1./prod(Z+eye(length(x)))
like image 154
Rasman Avatar answered Feb 21 '23 06:02

Rasman


Kristian, there are a lot of ways to vectorize code. You've already gotten two. (And I agree with shakinfree: you should always consider 1) how long it takes to run in non-vectorized form (so you'll have an idea of how much time you might save by vectorizing); 2) how long it might take you to vectorize (so you'll have a better sense of whether or not it's worth your time; 3) how many times you will call it (again: is it worth doing); and 3) readability. As shakinfree suggests, you don't want to come back to your code a year from now and scratch your head about what you've implemented. At least make sure you've commented well.

But at a meta-level, when you decide that you need to improve runtime performance by vectorizing, first start with small (3x1 ?) array and make sure you understand exactly what's happening for each iteration. Then, spend some time reading this document, and following relevant links:

http://www.mathworks.com/help/releases/R2012b/symbolic/code-performance.html

It will help you determine when and how to vectorize.

Happy MATLABbing!

Brett

like image 45
Brett Shoelson Avatar answered Feb 21 '23 07:02

Brett Shoelson