matlabmatlab-figurematlab-guide

Plotting structure array in Matlab


I have a structure array (98*1) in MATLAB:

enter image description here

Now I am trying to plot a graph by using 2 particular fields (say x and y). The values of x and y are present on each of these 98 rows. Trying the following command to plot gives error.

plot(ans{1:98,1}.x,ans{1:98,1}.y)

Expected one output from a curly brace or dot indexing expression, but there were 98 results.

Error in just (line 1) plot(ans{1:98,1}.x,ans{1:98,1}.y)

Need help in knowing what I am doing wrong, and how to correct it.


Solution

  • You probably need cellfun with an anonymous function (or a for loop) to extract the x and y fields from each cell's contents:

    plot(cellfun(@(t) t.x, ans(1:98,1)), cellfun(@(t) t.y, ans(1:98,1)))
    

    Note:

    It would be much easier if your data were organized in a more convenient manner, such as a 98×1 struct array with fields x and y, or better yet two numeric vectors x and y.