【问题标题】:Passing Objects as Parameters to a Function: MATLAB [duplicate]将对象作为参数传递给函数:MATLAB [重复]
【发布时间】:2021-01-17 23:54:08
【问题描述】:

我有一个带有按钮的基本 GUI,您可以按下该按钮来选择导出路径,并带有一些文本显示选择的导出路径是什么。默认情况下,文本会显示当前工作目录,直到您选择不同的目录。

我将所有必需的变量和对象作为回调函数 (ExportPath) 中的参数传递。

exportPath_Button = uibutton(exportSelection_Group, 'Position', [9 .* exportSelection_Group.Position(3) ./ 10 - 10, 5, exportSelection_Group.Position(3) ./ 10, exportSelection_Group.Position(4) - 30], 'Text', 'Select Path', 'ButtonPushedFcn', {@ExportPath, currentFolder, exportFolder, exportPath_Text});
function ExportPath(~, ~, currentFolder, exportPath, exportPath_Text)
folderSelection = uigetdir(currentFolder, 'Export Folder');
switch folderSelection
    case 0
        return
    otherwise
        exportPath = folderSelection;
        exportPath_Text.Text = ['Export path: ', currentFolder];
end
end

为什么函数只会改变函数空间对象,而不是基础对象,尽管直接将基础对象作为参数传递?

然而,在我让一些图像在另一个函数中可见的情况下,将图像作为参数传递给回调函数(如下所示),效果很好,并且图像改变了它们的可见性?

CPU_Group = uibuttongroup(mainWindow, 'Position', [10, (uiSize - uiSize ./ 3) - 10, innerSize(1), uiSize ./ 10], 'Title', 'CPU', 'TitlePosition', 'centertop', 'SelectionChangedFcn',{@CPUSelection, amd_Image, intel_Image});
function CPUSelection(~, event, AMD_Logo, Intel_Logo)
    switch event.NewValue.Text
        case "AMD"
            AMD_Logo.Visible = 'on';
            Intel_Logo.Visible = 'off';
        case "Intel"
            Intel_Logo.Visible = 'on';
            AMD_Logo.Visible = 'off';
    end
end

非常感谢!

【问题讨论】:

  • MATLAB 始终按值传递参数。有些对象是句柄对象,它们引用了未复制的资源。修改句柄对象实际上修改了指向的资源。您应该阅读 MATLAB 文档的相关部分,它们写得很好,很有启发性。

标签: function matlab parameter-passing


【解决方案1】:

您的对象是否继承自 handle?如果不是,那么它们是按值传递、写入时复制(“CoW”)对象,并且您的函数最终在原始对象的 copy 上运行,并且原始对象未更改。如果您想要传递引用行为和共享可变状态,请让您的对象继承自 handle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多