【问题标题】:Loading filename stored in string and then plotting data加载存储在字符串中的文件名,然后绘制数据
【发布时间】:2012-08-05 21:34:18
【问题描述】:

我正在尝试创建一个脚本,该脚本会询问用户稍后将绘制其内容的 txt 文件的文件名。

filename = input('What is the filename (without the extension) e.g. RCP6: ','s');
if isempty(filename)
    filename=input('What is the filename (without the extension) e.g. RCP6: ','s');
end

ext =  input('What is the filetype (extension) e.g. .txt: ','s');
if isempty(ext)
    ext=input('What is the filetype (extension) e.g. .txt: ','s');
end

filew = strcat(filename,ext)

load(filew)
A = filename
Y = A(:,1)
E = A(:,2)

plot(Y,E)
xlabel('calendar year')
ylabel('annual fossil carbon emissions (GtC)')

正如所写,代码正确连接了文件名和分机,但是,似乎 load (filew) 没有正确加载该文件,因为给定文件名 = RCP3PD,例如 Y = R 和 E = C,而不是 Y存储 RCP3PD.txt 中的第一列值?

有什么建议吗?我已经看到其他“从字符串加载文件”线程引用了 sprintf() 函数 - 这适用于这里吗?

【问题讨论】:

  • 为什么在 LOAD 调用后有A = filename?你的 MAT 文件里面还有什么?输入以下内容:whos -file myFile.mat 以查看其内容
  • 也可以考虑使用像UIGETFILE 这样的函数,而不是在命令行上请求输入。示例见here

标签: matlab file-io mat-file


【解决方案1】:

当您加载数据时,您需要将其另存为某种东西。所以:

load(filew)

应该是这样的

data = load(filew);

然后访问您的变量只需使用:

A = data.A; % assume that data is a struct with a field named A
Y = A(:,1);
E = A(:,2);

其他想法

您可以考虑将输入文件名的逻辑更改为以下内容:

valid = 0;
while(valid==0)
  filename = input('What is the filename (without the extension) e.g. RCP6: ','s');
  ext =  input('What is the filetype (extension) e.g. .txt: ','s');
  if exist([filename, ext], 'file')
    valid = 1;
  end
end

不是检查文件名是否为空,而是检查用户是否提供了实际存在的文件名/扩展名对。如果没有,请继续询问,直到他们询问为止。

如果你想变得花哨,你可以使用uigetfile 而不是要求用户输入文件名。这会向用户显示一个文件选择器窗口,这样您就知道他们选择了一个有效的文件。此外,它还允许您过滤用户可以选择的文件。

【讨论】:

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