Recall workspace variable in a function

15 ビュー (過去 30 日間)
Carlo Alberto Carissimi
Carlo Alberto Carissimi 2018 年 12 月 4 日
コメント済み: Stephen23 2018 年 12 月 4 日
Hi there!
I'm in trouble with this matlab function that i wrote.
function write_txt(filename)
Title_1 = 'Results';
Label_1 = ' Value1 ';
Label_2 = ' Value2 ';
Label_3 = ' Value3 ';
Mo_1 = {'Results'};
Data_1 = [x y z];
fid = fopen(filename,'w+t');
if fid < 0
fprintf('error opening file\n');
return;
end
fprintf(fid,'%s\n',Title_1);
fprintf(fid,'\n');
fprintf(fid,' %s%s%s\n',Label_1,Label_2,Label_3);
for ii= 1:1
fprintf(fid,'%5s: ',Mo_1{ii});
fprintf(fid,'%5.2f,%5.2f\n',Data_1(ii,:));
end
fclose(fid);
end
Basically this function write a .txt with all my results from another matlab script. The variable calculted in another matlab script (x,y,z) should be write on the txt file.
When i try to make the .txt file through the Command Window, Matlab give me this error:
Undefined function or variable 'x'.
Error in write_txt (line 7)
Data_1 = [x y z];
While the x,y,z variables are defined. Someone can help me?
  3 件のコメント
Carlo Alberto Carissimi
Carlo Alberto Carissimi 2018 年 12 月 4 日
Hi! I tried, gave me this:
>> write_txt
Not enough input arguments.
Error in write_txt (line 7)
Data_1 = [x 2 3];
Stephen23
Stephen23 2018 年 12 月 4 日
@Carlo Alberto Carissimi: you need to provide the required input arguments when you call the function, e.g.:
>> write_txt('myfile.txt',1,5,23)
How to call functions is a very basic MATLAB concept that is explained in the introductory tutorials:

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

回答 (2 件)

madhan ravi
madhan ravi 2018 年 12 月 4 日
編集済み: madhan ravi 2018 年 12 月 4 日
Define x y z before using it? Because matlab won't show that error if the variables are in workspace already.
  4 件のコメント
Carlo Alberto Carissimi
Carlo Alberto Carissimi 2018 年 12 月 4 日
>> whos x
Name Size Bytes Class Attributes
x 1x1 8 double
madhan ravi
madhan ravi 2018 年 12 月 4 日
so why not just define it inside the function since it's a scalar?

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


Walter Roberson
Walter Roberson 2018 年 12 月 4 日
the variables are not define in the workspace active in the function .They might possibly be in the base workspace and if so could be pulled from there if really needed . but better would be if you pass their values to the function as additional arguments.
  2 件のコメント
Carlo Alberto Carissimi
Carlo Alberto Carissimi 2018 年 12 月 4 日
Hi! Thank you for the response. I understand the problem, you might know how can i solve it? Or can you suggest me how to search it on google?
Stephen23
Stephen23 2018 年 12 月 4 日
" I understand the problem, you might know how can i solve it?"
Exactly as Walter Roberson and I already wrote, you should pass those values as input arguments.

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

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by