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 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Samuel Mousley
am 15 Jan. 2020
Kommentiert: Samuel Mousley
am 17 Jan. 2020
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 Kommentare
Image Analyst
am 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.
Akzeptierte Antwort
Sindar
am 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Labels and Annotations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!