外部.m文件中的Matlab app调用函数

Matlab app call function in external .m file

我想在应用程序中调用 getPhoto(),而 getPhoto() 是同一目录中另一个 .m 文件的函数。

应用代码

properties (Access = public)
    fullname % Description
    ImageFile % Description
end
  

% Callbacks that handle component events
methods (Access = private)

    % Button pushed function: CaricaimmagineSRButton
    function CaricaimmagineSRButtonPushed(app, event)
        getPhoto();
        test = app.fullname;
        answer = questdlg('do you wanna crop?', ...
            'Dessert Menu', ...
            'Yes', 'No','No');
        % Handle response
        switch answer
            case 'Yes'
                app.ImageFile = imcrop(app.ImageFile);
                close Figure 1;
            case 'No'
        end
        
        app.ImageFile = imresize(app.ImageFile, [300 200]);
        app.TextArea.Visible = false;
        app.UIAxes.Visible = true;
        imshow(app.ImageFile, 'Parent', app.UIAxes);
        
    end

getPhoto() 代码

function getPhoto()
cd('C:\Users\Gianl\Documents\MATLAB\app\test\Images');
        
[filename,filepath] = uigetfile({'*.*;*.jpg;*.png;*.bmp;*.oct'}, 'Select File to Open');

cd('C:\Users\Gianl\Documents\MATLAB\app');

 app = app2;
 app.fullname = [filepath,filename];
 app.ImageFile = imread(app.fullname);
 end

我想用 getPhoto() 选择照片并将名称和照片传递给应用程序到应用程序的属性中。

您可以使用 getPhoto 函数 return 只获取文件名和图像,而无需修改应用数据结构。但如果你非要这样做,你就得修改你的代码:

% Change the callback to 
app = getPhoto( app);

% Change the getPhoto function as below
function app = getPhoto( app)

    cd('C:\Users\Gianl\Documents\MATLAB\app\test\Images');
    
    [filename,filepath] = uigetfile({'*.*;*.jpg;*.png;*.bmp;*.oct'}, 'Select File to Open');

    cd('C:\Users\Gianl\Documents\MATLAB\app');

     app.fullname = [filepath,filename];
     app.ImageFile = imread(app.fullname);
 end

但更好的解决方案是

% In the callback change getPhoto() to
[app.fullname, app.ImageFile] = getPhoto();

% Modify the getPhoto function as below
function [fullname, ImageFile] = getPhoto()

    cd('C:\Users\Gianl\Documents\MATLAB\app\test\Images');
    
    [filename,filepath] = uigetfile({'*.*;*.jpg;*.png;*.bmp;*.oct'}, 'Select File to Open');

    cd('C:\Users\Gianl\Documents\MATLAB\app');

     fullname = fullfile( filepath, filename);
     ImageFile = imread(app.fullname);
 end