Python转Matlab转换?

2024-06-10 02:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是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转换尝试:

^{pr2}$

Tags: 代码版本helperlenreturnif排序def
2条回答

这里有几个问题:

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

  2. 实际上,您需要为for循环创建一个值数组来循环。为此,使用冒号创建一个从2到{}的数组。在

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

  4. 要翻转值,您可以简单地按如下方式进行赋值:

    ^{2美元

综合起来,你会得到这样的结果:

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

您的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代码是错误的:

^{pr2}$

相关问题 更多 >