简体   繁体   中英

Undefined function 'max' for input arguments of type 'cell'

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

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] 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')) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM