Cannot seem to save data to a file within a class

3 ビュー (過去 30 日間)
matquest
matquest 2018 年 2 月 27 日
コメント済み: per isakson 2018 年 3 月 3 日
I have a class which needs to write data to files. However, when I try to write the data, it gives a "variable not found" error, despite the variable being declared in the lines immediately preceding the call. I can manually run the code from the matlab command line and it does what I expect, so I think that the code is fine, but by being put into a class it somehow changes where the variables live. This is a shortened (working) version of what I have:
classdef SaveFiles < handle
properties
data;
fileLoc;
end
methods
function s = SaveFiles(loc)
s.fileLoc = loc;
end
function s = addData(s, data)
s.data = data;
end
function s = writeData(s)
data = s.data;
evalin('base', sprintf('save(''%s'', ''data'')', s.fileLoc));
end
end
end
From the matlab command line:
>> sf = SaveFiles('<file_loc>');
>> a = 1;
>> sf.addData(a);
>> sf.writeData();
This last line causes the following exception:
Error using save
Variable 'data' not found.
Error in SaveFiles/writeData (line 18)
evalin('base', sprintf('save(''%s'', ''data'')', s.fileLoc));
I'm completely stumped. Is there something obvious I'm just overlooking?

採用された回答

per isakson
per isakson 2018 年 3 月 2 日
編集済み: per isakson 2018 年 3 月 2 日
Yes, there is. To make it work, replace
evalin('base', sprintf('save(''%s'', ''data'')', s.fileLoc));
by
save( s.fileLoc, 'data' )
Why do you think you need to execute save in the base workspace? The variable data is not available in the base workspace, but in the workspace of the method.
.
Then there is a second issue. With handle objects, there is no need to return the object variable in methods, e.g. replace
function s = addData(s, data)
by
function addData(s, data)
However, the constructor shall return the object variable. See Comparison of Handle and Value Classes
  4 件のコメント
matquest
matquest 2018 年 3 月 2 日
I was merely mentioning that using eval rather than evalin also worked for the same reason, not suggesting that it was "better" in any sense.
per isakson
per isakson 2018 年 3 月 3 日
"I "need" to return the object for consistency with the rest of the codebase" Fine, then you do it for a reason, not by mistake - which I suspected.

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

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by