How can I automatically set a plots xlabel and ylabel to the variable names of x and y, when x and y are structure fields?
4 views (last 30 days)
Show older comments
I use matlab plots (such as scatter) on a daily basis for looking at data.
It is very tedious to set the xlabel and ylabel everytime so I wrote a small function to automatically set the labels to the variable name:
function myscatter(x,y)
scatter(x,y)
xname=inputname(1);
yname=inputname(2);
xlabel(xname);
ylabel(yname);
end
Then:
foo=(1:10)
bar=(1:10)
myscatter(foo, bar)
This creates a scatter plot where the x label is already named 'foo' and the y label is already named 'bar'.
This works great when x and y are just variables stored in the workspace.
However I generally work with tables or structures of data, and the function inputname will return blank when dot indexing is used, i.e: data.foo
What I would like is to be able to create a scatter plot with data from a table or structure and still have the x and y label automatically named.
If I enter:
data.foo=(1:10)
data.bar=(1:10)
myscatter(data.foo, data.bar)
I would like it to return the scatter plot with the x and y labels as 'foo ' and 'bar'?
2 Comments
Image Analyst
on 15 Jan 2020
Why not
xlabel('foo');
ylabel('bar');
If you're going to refer to those field of data when you pass them into myscatter(), then you must already know what the field names are, so just use them.
Accepted Answer
Sindar
on 16 Jan 2020
Assuming your data will always be in two fields of the same structure:
function myscatter(data,x_field,y_field, varargin )
assert(isfield(data,x_field),'Field %s not found',x_field)
assert(isfield(data,y_field),'Field %s not found',y_field)
scatter(data.(x_field),data.(y_field),varargin{:});
xlabel(x_field);
ylabel(y_field);
end
For use like this:
data.foo=(1:10)
data.bar=(1:10)
myscatter(data,'foo', 'bar')
Similar or less typing in function call and allows passing field names as variables.
Bonus: it should accept any optional arguments that scatter does
More Answers (0)
See Also
Categories
Find more on Labels and Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!