Take string from cell array for name of variable in matlab workspace

前端 未结 1 351
一生所求
一生所求 2021-01-28 11:25

I have a large amount of .csv files from my experiments (200+) and previously I have been reading them in seperately and also for later steps in my data handling this is tedious

相关标签:
1条回答
  • 2021-01-28 12:17

    You don't actually want to do this. Even the Mathworks will tell you not to do this. If you are trying to use variable names to keep track of related data like this, there is always a better data structure to hold your data.

    One way would be to have a cell array

    data = cell(size(input(:,1)));
    for n = 1:size(input,1)
        data{n} = csvread(strcat(input{n,1},'k.csv'),input{n,2},0);
    end
    

    Another good option is to use a struct. You could have a single struct with dynamic field names that correspond to your data.

    data = struct();
    for n = 1:size(input,1)
        data.(input{n,1}) = csvread(strcat(input{n,1},'k.csv'),input{n,2},0);
    end
    

    Or actually create an array of structs and hold both the name and the data within the struct.

    for n = 1:size(input, 1)
        data(n).name = input{n,1};
        data(n).data =  csvread(strcat(input{n,1},'k.csv'),input{n,2},0);
    end
    

    If you absolutly insist on doing this (again, it's is very much not recommended), then you could do it using eval:

    for n = 1:size(input, 1)
        data = csvread(strcat(input{n,1},'k.csv'),input{n,2},0);
        eval([input{n, 1}, '= data;']);
    end
    
    0 讨论(0)
提交回复
热议问题