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 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Image Analyst
2020 年 1 月 15 日
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.
採用された回答
Sindar
2020 年 1 月 16 日
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
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Labels and Annotations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!