MATLAB Answers

Why doesn't Matlab know the variable from appdesigner despite it is globalized into matlab workspace ?

1 view (last 30 days)
farzad
farzad on 19 Mar 2020
Commented: farzad on 19 Mar 2020
Hi All
I have written an app that using a pushbutton receives the working directory folder adress from the user and changes the matlab wd to that. the other push button is to run an mfile in thatdirectory and then cd() to some subfolder.
Despite I see the global variable shared between app and workspace ,it seems that matlab can not use it and therefore the cd() does not work cause the variable is seen as empty despite it's not
here is the app code :
properties (Access = public)
%selectedPath: path selected by user in ButtonPushed function
selectedPath= 'C:\' % Description
end
methods (Access = private)
% Button pushed function: ChooseDirectoryButton
function ChooseDirectoryButtonPushed(app, event)
global currentFolder
app.selectedPath = uigetdir();
app.UIFigure.Visible = 'on';
currentFolder=app.selectedPath;
cd(currentFolder)
end
% Button pushed function: ExecuteButton
function ExecuteButtonPushed(app, event)
global currentFolder;
currentFolder=app.selectedPath;
assignin('base','currentFolder',currentFolder);
goFolder = strcat(currentFolder,'\Fsolver.m');
run(goFolder)
app.UIFigure.Visible = 'on';
end
end
and the first lines of the mfile :
global currentFolder
inputs =strcat(currentFolder,'\Input')
cd(inputs)
these are the errors :
Error using cd
Cannot CD to \Input (Name is nonexistent or not a directory).
Error in mysolver (line 37)
cd(inputs)
Error in run (line 91)
evalin('caller', strcat(script, ';'));
Error in apprivate/ExecuteButtonPushed (line 39)
run(goFolder)
Error using matlab.ui.control.internal.controller.ComponentController/executeUserCallback (line 309)
Error while evaluating Button PrivateButtonPushedFcn.

  4 Comments

Show 1 older comment
farzad
farzad on 19 Mar 2020
if I remove the line
global currentFolder
from the MFile, then Matlab does not even know the variable at all. if I do, then it knows currentFolder only as an empty variable , even despite I have used assignin
Undefined function or variable 'currentFolder'.

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 19 Mar 2020
farzad - rather than using a global variable, can't you just use pwd to identify the current working directory? So the code in your m file would then become
inputPath = fullfile(pwd, 'Input')
cd(inputPath)
where fullfile is used to build the path. Of course the problem here is on the next line you will changed directory to that folder. Is that necessary? Could you just use inputPath for any code that tries to read or write to file?

More Answers (0)

Sign in to answer this question.