'cell'类型的输入参数的未定义函数'max'

时间:2015-07-07 03:21:16

标签: matlab

我正在尝试绘制输入数据的条形图并在每个条上添加数据标签,当我运行程序时,我得到一个错误为“未定义函数'max',用于'cell'类型的输入参数。”我的代码是......

 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

当我输入“data = [3 6 2 9 5 1]”时,程序运行良好

1 个答案:

答案 0 :(得分:1)

Matlab是一种无类型语言,所以你不知道y实际上是什么类型。当您尝试data = [3 6 2 9 5 1]并致电class(y)时,您将得到double作为答案,在此示例中是实数max()可以处理的向量。 但是,当您使用data = [3 6 2 ; 9 5 1]时,您会得到不同的y

>> class(y)

ans =

cell

>> y

y = 

    [1x2 double]
    [1x2 double]
    [1x2 double]

>> 

这意味着y不是矢量也不是矩阵,而是cell数组,它将三个双向量组合在一起。 max()不知道如何处理cell数组并为您提供

  

类型为cell

的输入参数的未定义函数'max'

错误。您可以在http://www.mathworks.com/help/matlab/data-types_data-types.html

上找到有关Matlab数据类型的更多信息

您可以通过将y变回向量来解决此错误,但由于您的labels也会更改,我会将您留在此处:

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