MATLAB Changing the name of a matrix with each iteration

后端 未结 3 1659
慢半拍i
慢半拍i 2020-12-02 01:10

I was just wondering if there is a clean way to store a matrix after each iteration with a different name? I would like to be able to store each matrix (uMatrix) under a dif

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 01:39

    There are really too many options. To go describe both putting data into, and getting data our of a few of these methods:

    Encode in variable names

    I really, really dislike this approach, but it seems to be what you are specifically asking for. To save uMatrix as a variable Sim5 (after the 5th run), add the following to your code at the end of the loop:

    eval([Sim ' = uMatrix;']);  %Where the variable "Sim" contains a string like 'Sim5'
    

    To access the data

    listOfStoredDataNames = who('Sim*')
    someStoredDataItem = eval(listOfStoredDataNames {1})  %Ugghh
    %or of you know the name already
    someStoredDataItem = Sim1;
    

    Now, please don't do this. Let me try and convince you that there are better ways.

    Use a structure

    To do the same thing, using a structure called (for example) simResults

    simResults.(Sim) = uMatrix;
    

    or even better

    simResults.(genvarname(Sim)) = uMatrix;
    

    To access the data

    listOfStoredDataNames = fieldnames(simResults)
    someStoredDataItem = simResults.(listOfStoredDataNames{1})
    %or of you know the name already
    someStoredDataItem = simResults.Sim1
    

    This avoids the always problematic eval statement, and more importantly makes additional code much easier to write. For example you can easily pass all simResults into a function for further processing.

    Use a Map

    To use a map to do the same storage, first initialize the map

    simResults = containers.Map('keyType','char','valueType','any');
    

    Then at each iteration add the values to the map

    simResults(Sim) = uMatrix;
    

    To access the data

    listOfStoredDataNames = simResults.keys
    someStoredDataItem = simResults(listOfStoredDataNames{1})
    %or of you know the name already
    someStoredDataItem = simResults('Sim1')
    

    Maps are a little more flexible in the strings which can be used for names, and are probably a better solution if you are comfortable.

    Use a cell array

    For simple, no nonsense storage of the results

    simResults{i} = uMatrix;
    

    To access the data

    listOfStoredDataNames = {};  %Names are Not available using this method
    someStoredDataItem = simResults{1}
    

    Or, using a slight level of nonesense

    simResults{i,1} = Sim;      %Store the name in column 1
    simResults{i,2} = uMatrix;  %Store the result in column 2
    

    To access the data

    listOfStoredDataNames = simResults(:,1)
    someStoredDataItem = simResults{1,2}
    

提交回复
热议问题