MATLAB - load file whose filename is stored in a string

拈花ヽ惹草 提交于 2019-12-10 12:44:31

问题


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:

{name}U{rate}

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

%# 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 strcat with say 'hello', 'U', and rate is 50, U will store 'helloU2' - how can I get strcat to append {rate} properly?

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

Many thanks!


回答1:


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



回答2:


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

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

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

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

Amro's suggestion of using UIGETFILE is ideal because it helps you to ensure you have a complete and correct path to the file.



来源:https://stackoverflow.com/questions/2303890/matlab-load-file-whose-filename-is-stored-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!