![](/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.