How to avoid a loop that contains if statements
Show older comments
Hi all,
I've got this loop that I'm trying to get rid of, in the hope of saving on computational time.
Here is the basic idea: I have a vector x_offgrid(:,j1,j2) that contains values that are off a grid. E.g. let the grid be x=[1 3 5 7 9], then x_offgrid might have values [1.7 5.5 3 8.5]. The vector w(:,j1,j2) contains weights associated with x_offgrid. Now, I want to find w_new(:,j1,j2) that gives me weights associated with x.
For now, my idea is to follow the steps
- Find the nearest neighbor of every value in x_offgrid in x. Call that vector x_ongrid. In my example, that is x_ongrid=[1 5 3 9]. The corresponding index is xind x_ongrid = x(xind)
- For every value in x_offgrid(i,j1,j2), a fraction of the weight w(i,j1,j2) goes to the nearest neighbor and the other fraction goes to the opposite neighbor (xindmin and xindmax). Those fractions are given by fractiondown and fractionup.
for j1=1:N1
for j2=1:N1
z=zeros(N2);
for i = 1:N2
if x_ongrid(i,j1,j2)>x_offgrid(i,j1,j2) % nearest neighbor is above
z(i,xind(i,j1,j2)) = w(i,j1,j2)*(1-fractiondown(i,j1,j2));
z(i,xindmax(i,j1,j2)) = z(i,xindmax(i,j1,j2)) ...
+ w(i,j1,j2)*fractiondown(i,j1,j2);
else % nearest neighbor is below
z(i,xind(i,j1,j2)) = w(i,j1,j2)*(1-fractionup(i,j1,j2));
z(i,xindmin(i,j1,j2)) = z(i,xindmin(i,j1,j2)) ...
+ w(i,j1,j2)*fractionup(i,j1,j2);
end
end
w_new_tmp(:,j1,:,j2)=z;
end
end
w_new=squeeze(sum(w_new_tmp,1));
Does anybody have a general hint what I could try? Or is it not really possible to rewrite this in a more efficient way? I thought about some type of interpolation function, but right now, I don't see how that could work.
Update: Thanks to Guillaume, I've been able to get rid of the if statement, but not of the loop. Now my code looks as follows:
for j1=1:N1
for j2=1:N1
for i = 1:N2
wn(i,j1,xind(i,j1,j2)+1,j2) = w_tmp(i,j1,j2)*weightup(i,j1,j2);
wn(i,j1,xind(i,j1,j2),j2) = w_tmp(i,j1,j2)*weightdown(i,j1,j2);
end
end
end
The problem is that xind might contain the same index multiple times. I'm not sure if I can make use of accumarray because I want to keep wn is a 4-dimensional matrix.
Thanks!
4 Comments
Image Analyst
on 17 Feb 2015
Explain, in words, what this does. What is TMz, xval, yp, w, etadown, wn, etaup, etc. Right now it just looks like alphabet soup - a jumble of random variables and I have trouble following it because there are no comments.
Tintin Milou
on 17 Feb 2015
Guillaume
on 17 Feb 2015
A point of terminology, a vector is a 1D matrix. x_offgrid(:, j1, j2) being a 3d matrix can't be a vector.
Tintin Milou
on 17 Feb 2015
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements 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!