【问题标题】:Assigned Octave variable not being saved to file分配的 Octave 变量未保存到文件
【发布时间】:2017-09-23 12:31:16
【问题描述】:

在下面的 Octave 脚本中,我循环浏览目录中的文件,将它们加载到 Octave 以对数据进行一些操作,然后尝试将操作后的数据(矩阵)写入名称源自的新文件输入文件的名称。将操作数据分配给与要保存的文件同名的变量名称。清除所有不需要的变量,保存命令应该保存/写入单个分配的变量矩阵到文件“new_filename”。

但是,最后一个保存/写入命令没有发生,我不明白为什么不发生。如果没有特定的变量命令,保存函数应该保存范围内的所有变量,在这种情况下,只有一个矩阵要保存。为什么这不起作用?

clear all ;

all_raw_OHLC_files = glob( "*_raw_OHLC_daily" ) ; % cell with filenames matching *_raw_OHLC_daily

for ii = 1 : length( all_raw_OHLC_files ) % loop for length of above cell

filename = all_raw_OHLC_files{ii} ; % get files' names

% create a new filename for the output file
split_filename = strsplit( filename , "_" ) ;
new_filename = tolower( [ split_filename{1} "_" split_filename{2} "_ohlc_daily" ] ) ;

% open and read file
fid = fopen( filename , 'rt' ) ;
data = textscan( fid , '%s %f %f %f %f %f %s' , 'Delimiter' , ',' , 'CollectOutput', 1 ) ;
fclose( fid ) ;
ex_data = [ datenum( data{1} , 'yyyy-mm-dd HH:MM:SS' ) data{2} ] ; % extract the file's data

% process the raw data in to OHLC bars
weekday_ix = weekday( ex_data( : , 1 ) ) ;
% find Mondays immediately preceeded by Sundays in the data
monday_ix = find( ( weekday_ix == 2 ) .* ( shift( weekday_ix , 1 ) == 1 ) ) ;
sunday_ix = monday_ix .- 1 ;

% replace Monday open with the Sunday open
ex_data( monday_ix , 2 ) = ex_data( sunday_ix , 2 ) ;

% replace Monday high with max of Sunday high and Monday high
ex_data( monday_ix , 3 ) = max( ex_data( sunday_ix , 3 ) , ex_data( monday_ix , 3 ) ) ;

% repeat for min of lows
ex_data( monday_ix , 4 ) = min( ex_data( sunday_ix , 4 ) , ex_data( monday_ix , 4 ) ) ;

% combines volume figures
ex_data( monday_ix , 6 ) = ex_data( sunday_ix , 6 ) .+ ex_data( monday_ix , 6 ) ;

% now delete the sunday data
ex_data( sunday_ix , : ) = [] ;

assignin( "base" , tolower( [ split_filename{1} "_" split_filename{2} "_ohlc_daily" ] ) , ex_data )

clear ans weekday_ix sunday_ix monday_ix ii filename split_filename fid ex_data data all_raw_OHLC_files

% print to file
save new_filename

endfor

【问题讨论】:

    标签: octave


    【解决方案1】:

    save new_filename 将当前工作区保存到文件名为“new_filename”的文件中。我猜你想要的是创建一个文件名存储在“new_filename”中的文件:

    save (new_filename);
    

    您当前“清除所有我不需要的然后存储整个工作区”的方法非常难看,如果这是您想要的唯一部分,您应该明确存储 ex_data

    save (new_filename, "ex_data");
    

    【讨论】:

    • 我知道这种方法很难看,但如果我在每个循环中明确保存“ex_data”,就会出现命名冲突,因为每个不同保存的文件“new_filename”都会包含名为“ex_data”的数据。如果我想加载两个或更多这样的文件,我加载的每个文件都会覆盖由前一个文件加载的数据“ex_data”。当然,我愿意为我的问题提供更优雅的解决方案。
    • @babelproofreader 然后你应该(我总是更喜欢这个)使用d = load ("yourfilename")这将文件加载到结构d中,你可以使用d.ex_data访问它
    • @babelproofreader btw,这个答案(第一部分)是否解决了您的问题?如果不是,你应该写一个MCVE(你的问题中的代码不是最小的,也不是可验证的
    • 是的,您回答的第一部分确实解决了我的直接问题,这就是为什么我对您的回答投了赞成票。几天后,如果没有其他贡献者在一些替代的整体方法方面提供“更好”的答案,我将正式接受你的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2018-11-23
    • 1970-01-01
    • 2013-03-03
    • 2011-02-07
    • 1970-01-01
    相关资源
    最近更新 更多