how to use the file name as the data name

Discussion in 'MATLAB' started by Yunfei Wang, Aug 31, 2009.

  1. Yunfei Wang

    Yunfei Wang Guest

    Hi

    I have a set of .txt files in one folder with different random names. What I need is to read the all the files automatically and set the file name as the data name. Can anyone help me with this problem, thank you!

    Yunfei
     
    Yunfei Wang, Aug 31, 2009
    #1
    1. Advertisements

  2. Yunfei Wang

    Jos Guest

    If the filename is a correct name for a variable, you could use those filenames as fieldnames of a struct. Alternatively, you could use array of structs. An example:

    AllFilenames {'data1','mydata','olddata'}
    for i=1:3,
    X = AllFilenames{i} ;
    AllData.(X) = load([X '.txt']) ;
    % Alternative
    % AllData(i).filename = X ;
    % AllData(i).data = load([X '.txt']) ;
    end

    hth
    Jos
     
    Jos, Aug 31, 2009
    #2
    1. Advertisements

  3. Yunfei Wang

    Rune Allnor Guest

    The simplest way is to use LOAD with no return argument:

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Name Size Bytes Class

    t 3x1 24 double array
    test 3x1 24 double array

    Grand total is 6 elements using 48 bytes
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    Rune
     
    Rune Allnor, Aug 31, 2009
    #3
  4. Yunfei Wang

    Yunfei Guest


    Actually, my problem is like below, I am using the code

    f=dir('*.txt');
    file_name = char(f.name);

    here, the file_name returns a char array <3X9 char>:

    file_name =

    aaa.txt
    bbbb.txt
    ccccc.txt

    Now, I want to use "aaa" as the name for data that contains in the "aaa,txt", same for "bbbb", and "ccccc".

    I hope it is clear this time. Thanks for your help!
     
    Yunfei, Sep 1, 2009
    #4
  5. Yunfei Wang

    Steven Lord Guest

    Don't do this -- if you want to process each of the files, just refer to
    f(k).name.
    Don't. See Q4.6 and 4.12 in the newsgroup FAQ.
     
    Steven Lord, Sep 1, 2009
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.