How do I get MATLAB to automatically build a column of cell array data based on an array of varying numerical values?

1 次查看(过去 30 天)
I've been asked to build an M-file to help automate some plotting activities which utilize the gscatter command. Specifically, use the functionality of gscatter, and apply specific verbiage for the legend based on varying values. I've read about numerous attempts to automate plot creation - a lot of which is practical and useful. But when it comes to automating plot creation using the gscatter command, info is a little scarce.
So I started off by using the MATLAB example for the gscatter function. I typed the following into MATLAB:
load carsmall;
gscatter(Weight,MPG,Model_Year,'','xos');
I got the same plot as shown here:
Next, I created a cell array column (equal in size to the Model_Year data) containg the actual model years (in words) and called it LegCol: LegCol = {'seventy';'seventy'; .....'seventy six';'seventy six';.....'eighty two';'eighty two'};
Finally, I re-issued the gscatter function:
gscatter(Weight,MPG,LegCol,'','xos');
I get the same plot as before and the legend now contains the model years (in words) - as expected.
The approach seems to work, but I need a way for MATLAB to automatically create the cell array LegCol (based on the model years) - instead of doing it by hand.
Is there a way to do this?

采纳的回答

A Jenkins
A Jenkins 2013-10-23
编辑:A Jenkins 2013-10-23
There are lots of ways. A couple simple examples you can play with to help you get started:
1)
year_names={70, 'seventy';
76, 'seventy six';
82, 'eighty two'};
for idx=1:size(Model_Year,1)
for jdx=1:size(year_names,1)
if Model_Year(idx)==year_names{jdx,1}
LegCol{idx}=year_names{jdx,2};
end
end
end
2)
for idx=1:size(Model_Year,1)
switch Model_Year(idx)
case 70
LegCol{idx}='seventy';
case 76
LegCol{idx}='seventy six';
case 82
LegCol{idx}='eighty two';
end
end
  1 个评论
Brad
Brad 2013-10-23
As it turns out, the case statements are perfect for small data sets. And the approach is solid (when I remember ALL of the curly bracketts). Thanks.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Bar Plots 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by