![](/img/trans.png)
[英]How to use strcmp() to compare a returned value of a function to a function call in a loop?
[英]Retain the value of loop variable even on making a call to another function in the loop
在調用函數gm
時,我想在下面提到的代碼中保留變量q
的值。
demo.m
是:
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
並且此代碼生成以下錯誤:
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);
gm
函數使用q
如下:
Iq=imread(sprintf('db/queries/%d.jpg',q));
當然,向函數調用中添加更多變量是解決此問題的最干凈方法。 但是,如果修改所調用的函數太麻煩,例如,因為您必須更改許多函數,直到到達要使用變量的那個函數,那么您可能需要考慮將此變量設置為全局變量 :
global YOURVARIABLE %choose a good name here to avoid
%overwriting existing global variables
現在您可以從任何其他函數的工作空間訪問YOURVARIABLE
盡管您必須在每個函數中分別聲明它 ,請參見: 在MATLAB中聲明全局變量
另外,使用它們時應格外小心:
http://www.mathworks.com/help/matlab/matlab_prog/share-data-between-workspaces.html
如文檔中所述,全局變量是有風險的,因為它們具有自己的工作區,可以在任何地方進行編輯,因此,如果多個函數使用相同的變量,則可能會得到意想不到的結果。 因此,僅應在真正必要時使用它們。
我將for
循環中的代碼修改為
sim(q,:)=gm(query_path,ref_paths,fq,fr,matches,K,q);
以及被調用函數gm
的定義為
gm(query_path,ref_paths,fq,fr,matches,K,q);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.