matlabmatlab-gui

Question regarding the scope of my global variable {matlab}


Gui i'm trying to do an assignment for my class and the undo button click should reload the previous transformation applied onto the image in case i wish to go back. The golabal variable is defined in the start of the code enter image description here

function LoadimgBtn_Callback(hObject, eventdata, handles)
% hObject    handle to LoadimgBtn (see GCBO)
[filename,pathname]=uigetfile('C:\Users\hassan\Desktop\DIP PROJECT IMGS\MonoChrome 
Images\*.jpg;*.png;*.jpeg');
file_path=strcat(pathname,filename);
og_img=imread(file_path);
axes(handles.org_img);
imshow(og_img);
prev_img=og_img;
axes(handles.intr_img);
imshow(prev_img);

As observed the global variable prev_img is utlized perfectly here however when i try to use the same variable in my undo code there is an error thrown that the variable does not exist.

function UndoBtn_Callback(hObject, eventdata, handles)

axes(handles.intr_img);

imshow(prev_img);

Error

I wish to utilize the same variable through the global variable method.


Solution

  • you need to call the global variable again in your function code

    function UndoBtn_Callback(hObject, eventdata, handles)
    
    axes(handles.intr_img);
    global prev_img % declaring a global variable "again"
    imshow(prev_img);
    

    Otherwise, you are overshadowing the global varibale with a local variable of the same name. (remember that you can also define function with the same name as a matlab function e.g. sum.) The thing is, that matlab does not know, that you want the variable to be global. The same is true for persistent variables. Once you define a global variable in your function, matlab checks if this (global) variable already exists and if it has already a value. You may want to have a look in the matlab-docs if my explanation wasn't intuitive enough.

    To clear a global variable, you need to call clearvars -global or clear all or clear global

    • To clear a global variable from all workspaces, use clear global variable.
    • To clear a global variable from the current workspace but not other workspaces, use clear variable.