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?

조회 수: 3 (최근 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
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.
Samuel Mousley
Samuel Mousley 2020년 1월 15일
Because my x and y labels are not always 'foo' and 'bar', they're whatever variables I want to look at in the data.
I realise I'm being a bit lazy, but I will change the variables shown in the plot many times in quick succession as I look through my data, and it's tedious to set the x and y label every single time through that method.

댓글을 달려면 로그인하십시오.

채택된 답변

Sindar
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
  댓글 수: 1
Samuel Mousley
Samuel Mousley 2020년 1월 17일
Thank you, that works well and as you say, actually cuts down the amount of typing.
I can also use the same approach to make it work with tables too!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Labels and Annotations에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by