简体   繁体   中英

Retain the value of loop variable even on making a call to another function in the loop

I want to preserve the value of variable q in the below mentioned code when it makes a call to the funtion gm .

demo.m is:

for q=1:Nqueries        
    disp(['Matching query ' db.queries{q}]);
    qPath=[db.folder '/' db.fqueryFolder '/' db.queries{q} '_' featMethod '_' num2str(PeakThreshold) '.mat'];
    fq=load(qPath);
    query_path=[db.folder '/' db.queryFolder '/' db.queries{q} '.jpg'];
    matches=cell(1,Nrefs);
    fr=cell(1,Nrefs);
    ref_paths=cell(1,Nrefs);
    for r=1:Nrefs
        rPath=[db.folder '/' db.frefFolder '/' db.references{r} '_' featMethod '_' num2str(PeakThreshold) '.mat'];
        ref_paths{r}=[db.folder '/' db.refFolder '/' db.references{r} '.jpg'];
        fr{r}=load(rPath);
        %Matching things
        [idx, dists] = vl_ubcmatch(fq.d,fr{r}.d,thRatio);
        matches{r}.idx=idx;
        matches{r}.dists=dists;
    end
    %We run the Generative Model
    sim(q,:)=gm(query_path,ref_paths,fq,fr,matches,K);
end

and this code generates following error:

Matching query 1
??? Undefined function or variable 'q'.

Error in ==> gm at 86
 Iq=imread(sprintf('db/queries/%d.jpg',q));

Error in ==> demo at 65
    sim(q,:)=gm(query_path,ref_paths,fq,fr,matches,K);

The gm function uses q as follows:

 Iq=imread(sprintf('db/queries/%d.jpg',q));

Adding more variables to the function call is the cleanest way of resolving this issue, of course. But if modifying the called function is too painful, eg because you'd have to change many functions until you reach the one where you want to use your variable, you might want to consider making this variable a global variable :

global YOURVARIABLE    %choose a good name here to avoid 
                       %overwriting existing global variables

YOURVARIABLE can now be accessed from any other function's workspace although you have to declare this in each function separately, see: Declaring a global variable in MATLAB

Also, you should be very careful when using them:

http://www.mathworks.com/help/matlab/matlab_prog/share-data-between-workspaces.html

As described in the documentation global variables are risky because they have their own workspace that can be edited from anywhere, so if the same variable is used by several functions you might get unexpected results. Therefore, they should only be used when really necessary.

I modified the code in the for loop to

sim(q,:)=gm(query_path,ref_paths,fq,fr,matches,K,q); 

and the definition of the called function gm as

gm(query_path,ref_paths,fq,fr,matches,K,q);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM