«

»

Jul
26

Extracting data from Matlab figures

Has it ever happened to you that you have a Matlab figure, but you forgot to save the corresponding data? It happened to me more than once and each time I have to remind myself how to get the data back. Finally, I decided to save the knowledge here for anyone who may run into the same problem.

The good thing about Matlab figures is that they hold all the data and it can be extracted fairly easily. I will cover extracting line data here, which is the most common. However, the procedure can be easily modified to other data types as well.

The figure below shows an example of multiple line graphs.

The code below can be used to extract all three sine functions from the above figure:

%get the handle of the current figure
fig = gcf;

%get the handles of the active axes
axes = get(fig, ‘Children’);

%get the handles of the data objects associated with each axis
data = get(axes, ‘Children’);

%these cell variables will hold the extracted data
x_data = {};
y_data = {};

%go through all line objects and extract X and Y data
for i=1:length(data)
    object_type = get(data{i}, ‘Type’);
    current_data = data{i};
    if iscell(object_type)
        for j=1:length(object_type)
            %check whether the current object matches the desired data type
            if strcmp(object_type{j}, ‘line’)
                %save extracted data
                x_data = vertcat(x_data, get(current_data(j), ‘XData’));
                y_data = vertcat(y_data, get(current_data(j), ‘YData’));
            end
        end
    else
        %check whether the current object matches the desired data type
        if strcmp(object_type, ‘line’)
            %save extracted data
            x_data = vertcat(x_data, get(current_data, ‘XData’));
            y_data = vertcat(y_data, get(current_data, ‘YData’));
        end
    end
end

If it is desired to extract other data types that may be present in the figure, it is necessary to change the second parameter in both “strcmp” functions and possibly how the data should be stored (for example, if the data represents a two-dimensional matrix as opposed vectors in this example).

Zeljko Medenica

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>