Python到Matlab的转换?

时间:2016-08-11 19:11:11

标签: python matlab

我在下面有这个python代码(用于冒泡排序)。下面是我尝试将其转换为MATLAB代码。我是MATLAB的新手,我正在进行实践转换。我希望得到关于我的转换准确/不正确的反馈。

python版本:

def bubble_sort(alist):
    return bubble_sort_helper(alist, len(alist))
def bubble_sort_helper(alist, n):
    if n < 2:
        return alist
    for i in range(len(alist)-1):
        if alist[i] > alist[i+1]:
            temp = alist[i]
            alist[i] = alist[i+1]
            alist[i+1] = temp
    return bubble_sort_helper(alist, n-1)

我尝试进行MATLAB转换:

function a = bubble_sort(alist)
    a = bubble_sort_helper(alist, size(alist))
end

function b = bubble_sort_helper(alist, n)
    if n < 2
        b = alist
    end
    for ii = size(alist)
        if alist(1) > alist (ii+1)
            temp = alist(ii)
            alist(ii) = alist(ii+1)
            alist(ii+1) = temp
        end
    end
    b = bubble_sort_helper(alistn n-1)

end

2 个答案:

答案 0 :(得分:2)

这里有几个问题:

  1. 您需要使用numel而不是size来获取数组中的元素数量。 size将为您提供每个维度的大小向量,numel将为您提供元素总数

  2. 您需要为for循环实际创建一个值数组才能循环。为此,请使用冒号创建从2n的数组。

    for ii = 2:n
    end
    
  3. 您使用ii作为循环变量,但尝试在循环内部使用i。选一个并坚持下去(最好不是i

  4. 要翻转这些值,您只需执行以下任务:

    alist([i-1, i]) = alist([i, i-1]);
    
  5. 总之,这会给你这样的东西:

    function a = bubble_sort(alist)
        a = bubble_sort_helper(alist, numel(alist))
    end
    
    function b = bubble_sort_helper(alist, n)
        if n < 2
            b = alist;
        else
            for k = 2:n
                if alist(k-1) > alist(k)
                    alist([k-1, k]) = alist([k, k-1]);
                end
            end
            b = bubble_sort_helper(alist, n-1);
        end
    end
    

答案 1 :(得分:1)

您的python版本效率低下:

def bubble_sort(alist):
    return bubble_sort_helper(alist, len(alist))
def bubble_sort_helper(alist, n):
    if n < 2:
        return alist
    for i in range(n-1):
        if alist[i] > alist[i+1]:
            alist[i], alist[i+1] = alist[i+1], alist[i]
    return bubble_sort_helper(alist, n-1)

你的matlab代码错了:

function a = bubble_sort(alist)
    a = bubble_sort_helper(alist, size(alist))
end

function b = bubble_sort_helper(alist, n)
    if n < 2
        b = alist;
    else
        for i = 2:n
            if alist(i-1) > alist(i)
                temp = alist(i-1);
                alist(i-1) = alist(i);
                alist(i) = temp;
            end
        end
        b = bubble_sort_helper(alist, n-1);
    end
end