MATLAB: Identifying and keeping duplicates but with a suffix

duplicatesvector

Hello, I have a column vector that I use for x values for a Bar Chart from data extracted from a UITable.
Y=cell2mat(data(:,4))
X=data(:,2);
Xdata = categorical(X);
X = reordercats(Xdata,X);
b1=bar(X,Y,'Parent',app.UIAxes2);
My x data (Column vector) is one of 3 numbers 405, 532 or 660.
The data can be any of these and with any number of repeats e.g
405
405
405
405
405
or
405
532
532
660
405
The problem is the bar chart cannot handle repeat values. I'd still like to plot and thought one way would be to identify repeats and place an _ with a number, but am not sure how to
e.g
405
405
405
405
405
becomes
405_1
405_2
405_3
405_4
405_5
and
405
532
532
660
405
becomes
405_1
532_1
532_2
660
405_2
Thanks for any help

Best Answer

  • OK, that helps...actually, that's not too hard and even easier than the grouped solution -- I don't quite follow what your data storage must be with the mixing of cell2mat for Y and not for X so I'll write as if both are simple double arrays -- you can adapt to whatever data actually is that we can't see--I would tend to avoid creating copies of the same data, but since this is apparently small samples, it won't be that expensive to do so here.
    [X,ix]=sort(X); % order by wave number
    Y=Y(ix); % arrange counts to correspond
    hBar=bar(Y,'Parent',app.UIAxes2); % plot against the ordinal position to avoid the duplicates
    xticklabels(categorical(X)) % use the categorical names as tick labels
    Can fixup the appearance as wanted from here...
    The alternative with the grouping solution would be
    >> [x y] % some made up sample data
    ans =
    405 529
    532 166
    532 602
    660 263
    405 655
    >>
    % the engine
    N=groupcounts(x); % count elements in each wave number
    Y=nan(numel(N),max(N)); % build the grouping array for bar()
    [X,~,ib]=unique(x); % get the unique wave numbers/groups and group identity
    yy=accumarray(ib,y,[],@(v) {v}); % separate by group to cell array
    for i=1:3, Y(i,1:N(i))=yy{i}; end % and put by row into the 2D double array
    figure
    hBar=bar(X,Y);
    xticklabels(categorical(X))
    set(hBar,'FaceColor','y')
    hAx=gca;
    hAx.Color='k';
    hAx.GridColor='w';
    hAx.GridAlpha=0.5;
    title('Gropued by Wave Number')
    grid on
    The above produced