【问题标题】:Matlab best approach to save data in filesMatlab将数据保存在文件中的最佳方法
【发布时间】:2018-06-12 21:36:58
【问题描述】:

在我的程序中,我添加了两个按钮来保存和加载默认参数。现在我将这些参数保存在一个 excel 文件中,我认为这样可以更快地读取,以防万一只想用这种方法查看 Matlab 之外的默认参数

A = {'Variable 1','Variable 2','Variable 3';
    var1,var2,var3};
filename = fullfile(folder,'name_file.xlsx');
sheet = 1;
xlRange = 'A1';
xlswrite(filename,A,sheet,xlRange) 

但我看到我第一次保存时需要很长时间(如果文件不存在,甚至最坏的情况),当我在第一次迭代中将参数加载回我的程序时也是如此。 我在想:有没有其他方法可以编写和读取 excel 文件以节省一些时间?否则我可以考虑使用 txt 文件而不是 excel

【问题讨论】:

  • 有什么特殊原因需要保存到 excel 文件而不是“.mat”文件吗?否则有这个alternate xlswrite
  • 实际上,这只是我想在没有打开 matlab 的情况下查看参数的第一件事。因为如果我使用“.mat”文件,我应该先打开 matlab 或选择用记事本打开文件。
  • 你的矩阵是数字的,你只是希望能够在excel中正常打开它?
  • 嗯,只有数字还是只有字符?
  • 不,我现在写了一个单元格变量,其中第一行是每个元素的名称(在 ascii 中),第二行是变量。

标签: matlab performance file


【解决方案1】:

csvwritexlswrite 快得多。您可以使用csvwrite 将其保存为逗号分隔的 csv 文件。您也可以使用 Excel 打开它,但 csvwrite 不接受 cell 数组作为输入。所以你需要将它保存为矩阵:

A = [var1,var2,va3];
csvwrite(filename,A);

【讨论】:

  • 您不仅试图从我这里窃取答案,而且还窃取了我们已经调查过的答案。您提出的答案不适合该问题。优雅
【解决方案2】:

我遇到了(稍微)类似的问题,并采用了以下方法(在我的情况下,这是因为我使用了 xlswrite,然后转移到没有它可用的系统。pad_to_string 需要一个文件名和一个单元格包含数字和字符串数据的数组。

不确定在 Matlab 中读回这种格式的文件有多容易,因为我从未尝试过,但我认为 csvread 应该可以处理。

function pad_and_write_to_csv(fname, data)

string_data = cellfun(@data_to_string,data,'UniformOutput',0);
size_data = cellfun(@length,data,'UniformOutput',0);

padded_data = cellfun(@(x) pad_string(x),string_data,'uniformoutput',0);
%From the char matrix, you can use the FPRINTF function to properly output strings to a text file, as shown below:

for i = 1:size(padded_data, 1)
    lines{i} = horzcat(padded_data{i,:});
    lines{i} = lines{i}(1:end-1); % strip trailing comma
end

fid = fopen(fname,'wt');
for i = 1:size(padded_data,1)
    fprintf(fid,'%s\n',lines{i});
end
fclose(fid);

在文件pad_string.m

function [ out ] = pad_string( in )

% a = length(in);
% out = [char(32*ones(1,str_length-a)), in];

out = [in, ','];

在文件data_to_string.m

function [ out ] = data_to_string( in )

in_datatype = class(in);

switch in_datatype
    case 'char'
        out = ['''', in ''''];
    case 'double'
        out = num2str(in);
end

【讨论】:

    猜你喜欢
    • 2012-02-07
    • 2014-07-12
    • 2013-01-08
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    相关资源
    最近更新 更多