string MATLAB - 加载文件名存储在字符串中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2303890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:40:51  来源:igfitidea点击:

MATLAB - load file whose filename is stored in a string

stringmatlab-load

提问by Mark

I am using MATLAB to process data from files. I am writing a program that takes input from the user and then locates the particular files in the directory graphing them. Files are named:

我正在使用 MATLAB 处理来自文件的数据。我正在编写一个程序,该程序接受用户的输入,然后在目录中定位特定文件,以绘制它们。文件命名为:

{name}U{rate}

{name}U{rate}

{name} is a string representing the name of the computer. {rate} is a number. Here is my code:

{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);

There are currently two problems:

目前有两个问题:

  1. When I do the strcatwith say 'hello', 'U', and rate is 50, U will store 'helloU2' - how can I get strcatto append {rate} properly?

  2. The load line - how do I dereference U so load tries to load the string stored in U?

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

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

Many thanks!

非常感谢!

采纳答案by Amro

Mikhail's comment above solves your immediate problem.

米哈伊尔上面的评论解决了您的紧迫问题。

A more user-friendly way of selecting a file:

一种更用户友好的选择文件的方式:

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

回答by gnovice

In addition to using SPRINTFlike Mikhail suggested, you can also combine strings and numeric values by first converting the numeric values to strings using functions like NUM2STRand INT2STR:

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

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

One issue with the string in Uis that the file has to be on the MATLAB pathor in the current directory. Otherwise, the variable NET_NAMEhas to contain a full or partial path like this:

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

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

Amro's suggestionof using UIGETFILEis ideal because it helps you to ensure you have a complete and correct path to the file.

Amro 的使用UIGETFILE的建议非常理想,因为它可以帮助您确保拥有完整且正确的文件路径。