Reputation: 31
I'm trying to plot bar chart for input data and to add data labels on each bar, when I run the program I got an error as "Undefined function 'max' for input arguments of type 'cell'." my code is...
data = [3 6 2 ;9 5 1];
figure; %// Create new figure
h = bar(data); %// Create bar plot
%// Get the data for all the bars that were plotted
x = get(h,'XData');
y = get(h,'YData');
ygap = 0.1; %// Specify vertical gap between the bar and label
ylim([0 12])
ylimits = get(gca,'YLim');
%// The following two lines have minor tweaks from the original answer
set(gca,'YLim',[ylimits(1),ylimits(2)+0.2*max(y)]);
labels = cellstr(num2str(data')) %//'
for i = 1:length(x) %// Loop over each bar
xpos = x(i); %// Set x position for the text label
ypos = y(i) + ygap; %// Set y position, including gap
htext = text(xpos,ypos,labels{i}); %// Add text label
set(htext,'VerticalAlignment','bottom', 'HorizontalAlignment','center')
end
when I give input as "data = [3 6 2 9 5 1]", the program runs fine
Upvotes: 0
Views: 2748
Reputation: 66
Matlab is a typeless language, so you don't know what type y
is actually going to be. When you try data = [3 6 2 9 5 1]
and call class(y)
you will get double
as an answer, which in this example is a vector of real numbers max()
can work on.
However when you use data = [3 6 2 ; 9 5 1]
, you get different y
:
>> class(y)
ans =
cell
>> y
y =
[1x2 double]
[1x2 double]
[1x2 double]
>>
Which means y
is not a vector nor a matrix but a cell
array that holds together three double vectors. max()
does not know how to work on cell
arrays and gives you
Undefined function 'max' for input arguments of type
cell
error . You can find more on Matlab data types on http://www.mathworks.com/help/matlab/data-types_data-types.html
You can fix this error by turning y
back into a vector, but as your labels
will also change I will leave you here:
data = [3 6 2 ;9 5 1];
figure; %// Create new figure
h = bar(data); %// Create bar plot
%// Get the data for all the bars that were plotted
x = get(h,'XData');
y = get(h,'YData');
ygap = 0.1; %// Specify vertical gap between the bar and label
ylim([0 12])
ylimits = get(gca,'YLim');
y=[y{1} y{2} y{3}]; %works in this particular example
%// The following two lines have minor tweaks from the original answer
set(gca,'YLim',[ylimits(1),ylimits(2)+0.2*max(y)]);
labels = cellstr(num2str(data'))
Upvotes: 1