0

I want to load an ASCII-file using this syntax:

load('10-May-data.dat')

The returned output variable name should be X10_May_data.

Is there a way to get the variable name in Matlab? If I want to use regular expression to do the translation, how can I do it? For example, put an X before any underscores or digits in the filename and replace any other non-alphabetic characters with underscores.

4
  • 2
    How was '10-May-data.dat' created? With save? Is it actually a MAT-file despite the extension? Commented Feb 3, 2016 at 0:05
  • 2
    And what does s = load('10-May-data.dat') return? Or are you just trying to do fname = '10-May-data.dat'; str = strsplit(fname,{'-','.'}); vname = ['X' strjoin(str(1:end-1),'_')]? Commented Feb 3, 2016 at 0:10
  • 2
    And if you are trying to do what @horchler said: please don't want to do that. Commented Feb 3, 2016 at 0:50
  • 1
    See: dynamic field referencing and the documentation for load Commented Feb 3, 2016 at 12:05

1 Answer 1

0

The who function returns the names of variables in matlab. It also has a built-in regexp for selecting certain items:

X10_May_data = [1 2 3];
save X10_May_data.mat X10_May_data
clear
load X10_May_data.mat
w = who('-regexp','X*')

w = 

    'X10_May_data'

You can then operate on w{1} to do any substitutions you want. For example, use the strrep function for simple modifications of a string:

newvar = strrep(w{1},'May','latest')

newvar =

X10_latest_data

For more complex modifications, use regexp or regexprep. When you have the new name, you can assign it with eval:

eval([newvar '=' w{1}])  % like typing "X10_latest_data = X10_May_data"

X10_latest_data =

    1     2     3

[edit] PS I agree with the comments that eval is usually a bad idea; but sometimes you just need to get something done :) For alternative approaches, see the matlab page on the topic.

Sign up to request clarification or add additional context in comments.

3 Comments

Using eval is almost always a terrible idea. Please see this answer of mine where I lengthily explain that.
RE: your edit. You can get something done just as quickly without using lazy code that is difficult for people to use/debug and impossible for MATLAB's JIT compiler to optimize.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.