【问题标题】:Adding size information of dataset to file name将数据集的大小信息添加到文件名
【发布时间】:2016-07-04 19:12:16
【问题描述】:

我有几个数据集,称为 '51.raw' '52.raw'... 直到 '69.raw' 在我的代码中运行这些数据集后,这些数据集的大小从 375x91x223 变为具有不同 y 的大小-尺寸(即“51.raw”输出:375x45x223;“52.raw”输出:375x50x223,...每个数据集不同)。

我想稍后使用此信息保存“.raw”文件名(即“51_375x45x223.raw”),并且还想使用新的数据集大小在我的代码中重新调整数据集。我已尝试这样做但需要帮助:

for k=51:69

data=reshape(data,[375 91 223]); % from earlier in the code after importing data

% then executes code with dimensions of 'data' chaging to 375x45x223, ...

length=size(data); dimensions.([num2str(k)]) = length; %save size in 'dimensions'.

path=['C:\Example\'];
name= sprintf('%d.raw',k);

write([path name], data);  
% 'write' is a function to save the dat in specified path and name (value of k). I don't know how to add the size of the dataset to the name.

稍后我想为这次迭代重塑数据集“数据”,并使用新的 y 维度值进行重塑。

i.e. data=reshape(data,[375 new y-dimension 223]);

您的帮助将不胜感激。谢谢。

【问题讨论】:

  • 为什么不将尺寸inside保存在标题行中?这比尝试使用文件名来传达有关其内容的信息要好得多
  • 感谢您的评论 Suever,输出保存为 .raw 文件。然后为了在其他软件(ImageJ)中打开它,如果其他人想做它会更方便。另外,您提到的也是我的想法,但我被要求将其更改为文件名,但我不确定如何。

标签: matlab loops rename filenames


【解决方案1】:

您可以轻松地将尺寸转换为将保存为文件的字符串。

% Create a string of the form: dim1xdim2xdim3x...
dims = num2cell(size(data));
dimstr = sprintf('%dx', dims{:});
dimstr = dimstr(1:end-1);

% Append this to your "normal" filename
folder = 'C:\Example\';
filename = fullfile(folder, sprintf('%d_%s.raw', k, dimstr));

write(filename, data);

话虽如此,最好将此维度信息包含在文件本身中,而不是依赖文件名。

附带说明,避免使用内部函数的名称作为变量名,例如lengthpath。这可能会导致未来出现奇怪和意外的行为。

更新

如果您需要解析文件名,您可以使用textscan 来做到这一点:

filename = '1_2x3x4.raw';

ndims = sum(filename == 'x') + 1;
fspec = repmat('%dx', [1 ndims]); 
parts = textscan(filename, ['%d_', fspec(1:end-1)]);

% Then load your data

% Now reshape it based on the filename
data = reshape(data, parts{2:end});

【讨论】:

  • 感谢 Suever 的帮助。您以后如何回忆新的 y 维度(例如 49)以从字符串中“重塑”?因此,对于第二个 for 循环,我希望它读取尺寸“dim1xdim2xdim3”然后重塑: data=reshape(data, [dim1 dim2 dim3])
  • @a.kk 添加了一些更新的代码以从文件名中读回尺寸
  • 谢谢苏弗!我试过运行它,但我的数据和运行的其他数据出现错误:“使用重塑时出错,要重塑元素的数量不能改变。”
  • 好的,我明白为什么了,我的错别担心。再次感谢:)
猜你喜欢
  • 2018-03-11
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 2018-07-13
  • 1970-01-01
  • 2021-11-03
相关资源
最近更新 更多