I have a structure array (98*1) in MATLAB:
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.
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:
()
indexing is used instead of {}
, because cellfun
expects a cell array as input (more information about indexing cell arrays here). Also, if you want to process the whole cell array you can skip indexing altogether and just use
plot(cellfun(@(t) t.x, ans), cellfun(@(t) t.y, ans))
The two anonymous functions @(t) t.x
and @(t) t.y
act on each cell's contents, namely a scalar struct, and extract from it the x
or y
field respectively. The results are packed by default into a standard (numerical) array by cellfun
.
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
.