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.

horchler
  • 18,384
  • 4
  • 37
  • 73
susanna
  • 1,395
  • 3
  • 20
  • 32
  • 2
    How was `'10-May-data.dat'` created? With `save`? Is it actually a MAT-file despite the extension? – horchler Feb 03 '16 at 00: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),'_')]`? – horchler Feb 03 '16 at 00:10
  • 2
    And if you are trying to do what @horchler said: please don't want to do that. – Andras Deak -- Слава Україні Feb 03 '16 at 00:50
  • 1
    See: [dynamic field referencing](http://blogs.mathworks.com/loren/2005/12/13/use-dynamic-field-references/) and [the documentation for `load`](http://www.mathworks.com/help/matlab/ref/load.html) – sco1 Feb 03 '16 at 12:05

1 Answers1

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.

mhopeng
  • 1,063
  • 1
  • 7
  • 17
  • 1
    [NOOOOO](https://static.squarespace.com/static/51b3dc8ee4b051b96ceb10de/51ce6099e4b0d911b4489b79/51ce61bde4b0d911b449f30f/1348785466046/1000w/Luke-No-Supercut-Star-Wars.jpg) – Andras Deak -- Слава Україні Feb 03 '16 at 23:08
  • 1
    Using `eval` is almost always a terrible idea. Please see [this answer of mine](http://stackoverflow.com/questions/32467029/how-to-put-these-images-together/32467170#32467170) where I lengthily explain that. – Adriaan Feb 03 '16 at 23:11
  • 1
    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. – sco1 Feb 04 '16 at 13:49