【问题标题】:MATLAB - load file whose filename is stored in a stringMATLAB - 加载文件名存储在字符串中的文件
【发布时间】:2013-06-16 19:58:32
【问题描述】:

我正在使用 MATLAB 处理文件中的数据。我正在编写一个程序,该程序从用户那里获取输入,然后在绘制它们的目录中找到特定文件。文件命名:

{name}U{率}

{name} 是表示计算机名称的字符串。 {rate} 是一个数字。这是我的代码:

%# get user to input name and rate
NET_NAME = input('Enter the NET_NAME of the files: ', 's');
rate = input('Enter the rate of the files: ');

U = strcat(NET_NAME, 'U', rate)
load U;

Ux = U(:,1);
Uy = U(:,2);

目前有两个问题:

  1. 当我执行 strcat 时说 'hello'、'U' 并且速率为 50,U 将存储 'helloU2' - 我怎样才能让 strcat 正确附加 {rate}?

  2. 加载行 - 如何取消引用 U 以便加载尝试加载存储在 U 中的字符串?

非常感谢!

【问题讨论】:

  • 1. filename = sprintf("%s.%d", name, rate)
    2. fdata = load(filename)

标签: string matlab-load


【解决方案1】:

Mikhail 的上述评论解决了您的直接问题。

一种更人性化的文件选择方式:

[fileName,filePath] = uigetfile('*', 'Select data file', '.');
if filePath==0, error('None selected!'); end
U = load( fullfile(filePath,fileName) );

【讨论】:

    【解决方案2】:

    除了像 Mikhail 建议的那样使用 SPRINTF 之外,您还可以通过首先使用 NUM2STRINT2STR 等函数将数值转换为字符串来组合字符串和数值:

    U = [NET_NAME 'U' int2str(rate)];
    data = load(U);  %# Loads a .mat file with the name in U
    

    U 中的字符串的一个问题是该文件必须位于 MATLAB path 或当前目录中。否则,变量NET_NAME 必须包含完整或部分路径,如下所示:

    NET_NAME = 'C:\My Documents\MATLAB\name';  %# A complete path
    NET_NAME = 'data\name';  %# data is a folder in the current directory
    

    使用UIGETFILEAmro's suggestion 非常理想,因为它可以帮助您确保拥有完整且正确的文件路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多