【问题标题】:Undefined function 'max' for input arguments of type 'cell''cell' 类型的输入参数的未定义函数 'max'
【发布时间】:2015-07-07 12:06:40
【问题描述】:

我正在尝试为输入数据绘制条形图并在每个条形上添加数据标签,当我运行程序时,我收到错误消息“未定义函数 '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]”时,程序运行良好

【问题讨论】:

    标签: matlab


    【解决方案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')) 
    

    【讨论】:

    • 或者您可以将maxcellfun 一起使用,而不必担心转换:max(cellfun(@max, y))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多