0

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.

4

2 回答 2

2

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.
于 2020-03-16T07:30:27.113 回答
0

Apparently in mat lab every time you use a global variable you have to re declare it within the scope of a function as well. I am not sure however I think it creates a local instance of the variable with the same name if i do no explicitly mention the keyword global within the scope of the function as i was doing so before.

in my case i had to mention global at two locations and it works. gloabl mention 1 enter image description here

于 2020-03-16T07:29:30.837 回答