MATLAB Answers


This question is closed. Reopen it to edit or answer.

Help with Vectorization of array operation

1 view (last 30 days)
Jeremy on 12 Nov 2014
Closed: MATLAB Answer Bot on 20 Aug 2021
So I've recently discovered vectorization, and with my previous code it caused the code to run at 10% the previous for-loop monster. I've attached the code in question, and I've also attached the switch function below as well.
The switch function takes two values, and chooses whichever value is closest to zero, similar to the equation below
if true
% code
M(a,b)= a, |a|<|b|
b, |b|<=|a|
My main problem was getting the DxtP, DxtM, DytP, and DytM values vectorized, as they use a current cell value and next cell value in the same operation. How would I vectorize this code? Any and all help is greatly appreciated!

Answers (1)

Geoff Hayes
Geoff Hayes on 13 Nov 2014
Jeremy - it may be helpful to provide a typical set of inputs to your LPhiReinit function so that we can test out the function and observe its current behaviour (since you haven't commented on what these inputs should be). Even just providing the dimensions of each input would be extremely helpful.
You may want to rename your third input mesh as this conflicts with a built-in function of the same name (even if the new name is meshVar).
Consider pre-sizing your matrices, DytP, DytM, DxtP, DxtM, etc. to avoid the re-sizing of the matrix on each iteration of the for loops. For example,
DxtP = zeros(meshVar(x),meshVar(x));
You could probably even combine the first four for loops into two (or fewer) for loops, as the initializations of all four matrices are independent of each other.
Try to make your current code as efficient as possible before vectorizing it. There seems to be a lot of duplication in the first argument to the switchfunc so think about how you could minimize repeated evaluations of that input.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!