Loading filename stored in string and then plotting data

710 Views Asked by At

I am attempting to create a script which asks the user for the filename of a txt file whose contents will later be plotted.

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

As written, the code correctly concatenates filename and ext, however, it does not appear that load (filew) correctly loads that file, since given a filename = RCP3PD for example, Y = R and E = C, instead of Y storing the first column of values from RCP3PD.txt?

Any Suggestions? I have seen other "load file from string" threads make reference to the sprintf() function - would that apply here?

1

There are 1 best solutions below

0
On BEST ANSWER

When you load the data you need to save it as something. So :

load(filew)

Should look like

data = load(filew);

Then to access your variables simply use:

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

Other Thoughts

You might consider changing the logic for typing a file name to something like this:

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

Instead of checking to see if the filename is empty check to see if the user has provided a filename/extension pair that actually exist. If not then keep asking until they do.

If you want to get fancy you might use uigetfile instead of asking the user to type in a filename. This presents the user with a file picker window and this way you know that they have picked a valid file. Additionally it allows you to filter what files the user can chose.