简体   繁体   中英

how to convert this Python nested for loop in MATLAB?

I need to convert the following Python nested for loop in MATLAB, but it just doesn't work.

for ii in where(obs != 0)[0]:
    ob = obs[ii]
    ncount = int(floor(top / ob))
    for jj in range(ncount):
        l_ind = max(int(floor((ob * (jj + 1) - width / 2.) / top * (G - 1))), 0)
        h_ind = min(int(ceil((ob * (jj + 1) + width / 2.) / top * (G - 1))), G - 1)
        ret[ii, l_ind : h_ind + 1] = tukey(h_ind - l_ind + 1, 0.5)

I personally don't need the "where(obs != 0)[0]" part, because my obs vector has no zeros along that dimension. So far, I tried the following:

for ii = 1:length(obs)
    ob = obs(ii);
    ncount = floor(top / ob);
    for jj = 1:ncount
        l_ind = max(floor((ob * (jj + 1) - width / 2) / top * (G - 1)), 0);
        h_ind = min(ceil((ob * (jj + 1) + width / 2) / top * (G - 1)), G - 1);
        ret(ii , l_ind : h_ind) = tukeywin(h_ind - l_ind + 1)';
    end
end

In Matlab, the tukey is called tukeywin and I don't need the extra 0.5 parameter, because it's default value. I also had to transpose the tukeywin as you can see, to match the size, otherwise gives me another error, as well as remove the + 1 from the h_ind, probably because in Python, index starts at 0 and in Matlab, it starts at 1. If I keep the + 1, then I would have to put + 2 in the tukeywin function, to match sizes on both sides of the equation.

But after this, it still doesn't work, I am having problems with that last line to generate the ret matrix. ret matrix is initialized with zeros and is size 1972 x 1025. the obs vector is of size 1972 x 1. G is 1025, width is 300, top is 22050. The obs vector contains numbers that range between 100-600 for example, so you should be able to re-create this nested loop.

It gives me error " Index in position 2 is invalid. Array indices must be positive integers or logical values ". I am assuming this refers to the ret(ii , l_ind : h_ind) part, the ii is good, it will go till the length of 1972, but the l_ind : h_ind is giving me the error I think. So I am not sure how to structure this in Matlab.

Without fully testing your code I think your issue is related to 0 vs 1 based indexing of arrays. You are limiting l_ind and h_ind to 0 and G-1. For Matlab you would want 1 and G.

I'm not exactly sure what you are doing in the floor/ceil statements to determine your indices but I suspect the logic will need tweaked a bit. The simplest solution is probably to just +1 the l_ind and h_ind lines. Otherwise you need to rework them with 1-based indexing...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM