Script not finding variable even when the variable is in my workspace

So I have a bunch of variables from a data file in my workspace and I'm making a script to plot a contour plot quickly and it works fine.
function contf(A,B,C)
a=min(A):(max(A)-min(A))/200:max(A);
b=min(B):(max(B)-min(B))/200:max(B);
[Aq,Bq]=meshgrid(a,b);
C=griddata(A,B,C,Aq,Bq);
contourf(Aq,Bq,C)
set(gca,'YDir','reverse');
set(gca,'xaxislocation','top');
end
However A and B are always X and Y, variables that are in my respectively in my workspace. When i try this shorter function its not working?
function qcontf(C)
A=X
B=Y
a=min(A):(max(A)-min(A))/200:max(A);
b=min(B):(max(B)-min(B))/200:max(B);
[Aq,Bq]=meshgrid(a,b);
C=griddata(A,B,C,Aq,Bq);
contourf(Aq,Bq,C)
set(gca,'YDir','reverse');
set(gca,'xaxislocation','top');
end
I just get
Undefined function or variable 'X'.
Error in qcontf (line 2) A=X

 採用された回答

Thorsten
Thorsten 2015 年 10 月 8 日
編集済み: Thorsten 2015 年 10 月 8 日

1 投票

The variables X and Y in your workspace are not known inside the function. You can use the following, but it's not considered good practice:
function qcontf(C)
global X
global Y
A=X
B=Y

3 件のコメント

aaron Harvey
aaron Harvey 2015 年 10 月 8 日
編集済み: aaron Harvey 2015 年 10 月 8 日
Awesome thank-you! I guess its bad practice since the script will only work if you know what's inside it, but for the way im using it I don't mind. I'm trying to find an extra-lazy way to make almost 100 contour plots, all with the same X&Y.
Thorsten
Thorsten 2015 年 10 月 8 日
But why don't you use the first version of your function with 3 arguments A, B, C and call it using
qcontf(X,Y,C)
Stephen23
Stephen23 2015 年 10 月 8 日
編集済み: Stephen23 2015 年 10 月 8 日
@aaron Harvey: don't learn the bad practice of using globals when you can simply pass the values as arguments. Using globals is considered a bad practice in most programming languages, and passing arguments is what MATLAB recommends:
" Best Practice: Passing Arguments"
"The most secure way to extend the scope of a function variable is to use function input and output arguments, which allow you to pass values of variables."
Compare to this list:
and thousands of questions on this forum resulting from the decision to use globals.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeScope Variables and Generate Names についてさらに検索

質問済み:

2015 年 10 月 8 日

編集済み:

2015 年 10 月 8 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by